简体   繁体   English

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

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

I am using ASP.NET MVC5, Entity Framework 6, Dependency Injection and Unit Of Work.我正在使用 ASP.NET MVC5、Entity Framework 6、依赖注入和工作单元。

I am facing issue while saving a new item in the database.我在数据库中保存新项目时遇到问题。 I am not able to get the newly generated ID of the just inserted item.我无法获得刚刚插入的项目的新生成的 ID。

Below is a sample of my code, just to know more about my issue:以下是我的代码示例,只是为了了解有关我的问题的更多信息:

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.我不知道实体框架,但问题对我来说很明显。

The line entity=_userRepository.Add(entity);该行entity=_userRepository.Add(entity); calls Add method of Repository.调用 Repository 的Add方法。 In your Add method in Repository, you are adding an entity and then mapping it back to DTO.在 Repository 的Add方法中,您添加了一个实体,然后映射回 DTO。 You are then returning mapped DTO.然后您将返回映射的 DTO。 Note that DTO is detached here from your entity.请注意,此处 DTO 与您的实体分离。 It cannot anymore reflect the changes in Entity.它不能再反映实体的变化。

Then in your service, you call _unitOfWork.Commit();然后在您的服务中,您调用_unitOfWork.Commit(); . . This flushes the changes to database and here actually the new ID is generated.这会将更改刷新到数据库,并且实际上生成了新的 ID。 This new ID is reflected in your entity.这个新 ID 反映在您的实体中。 But as you are dealing with DTO which is no more connected to Entity, you cannot see that newly generated ID.但是当您处理不再连接到实体的 DTO 时,您看不到新生成的 ID。

What is the solution then?那有什么解决办法呢? I do not know, this depends on your overall architecture.我不知道,这取决于你的整体架构。

  1. Return the entity without mapping it with DTO.返回实体而不用 DTO 映射它。
  2. Commit inside repository instead of Service.提交内部存储库而不是服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM