如何在使用依赖注入和工作单元时获取生成的项目 ID?

How to get generated item ID while using Dependency Injection and Unit Of Work?

我正在使用 ASP.NET MVC5,Entity Framework 6,依赖注入和工作单元。

我在数据库中保存新项目时遇到问题。我无法获取刚刚插入的项目的新生成的 ID。

下面是我的代码示例,只是为了更多地了解我的问题:

Here's my service

public class UserService : IUserService
{
    IUnitOfWork _unitOfWork;
    IUserRepository _userRepository;

    public UserService(IUnitOfWork unitOfWork, IUserRepository UserRepository)
    {
        _unitOfWork = unitOfWork;
        _userRepository = UserRepository;
    }
    public int Create(UserDTO entity)
    {
        if(entity == null)
        {
            throw new ArgumentNullException("entity");
        }

        entity = _userRepository.Add(entity);
        _unitOfWork.Commit();

        return entity.UserID;
    }
}

Here's my repository

public virtual TEntityDTO Add(TEntityDTO entity)
{
    var item = Mapper.Map<TEntityDTO, TEntity>(entity);
    var createItem = Mapper.Map<TEntity, TEntityDTO>(context.Set<TEntity>().Add(item));
    return createItem;
}

Here's my unit of work

public int Commit()
{
    // Save changes with the default options
    return _dbContext.SaveChanges();
}

I do not know Entity Framework but the problem looks obvious to me.

entity=_userRepository.Add(entity);调用了Repository的Add方法。在 Repository 中的 Add 方法中,您正在添加一个实体,然后将其 映射 返回到 DTO。然后您将返回映射的 DTO。请注意,DTO 在这里与您的实体分离。它不能再反映实体中的变化。

然后在您的服务中,您调用 _unitOfWork.Commit();。这会将更改刷新到数据库,并且实际上会在此处生成新 ID。这个新 ID 反映在您的实体中。但是当您处理不再连接到实体的 DTO 时,您看不到新生成的 ID。

那有什么办法呢?不知道,这个要看你的整体架构。

  1. Return 未使用 DTO 映射的实体。
  2. 在存储库而不是服务中提交。