![](/img/trans.png)
[英]EF Core: The instance of entity type cannot be tracked and context dependency injection
[英]EF Core with Automapper throw Exception 'Entity type cannot be tracked'
我在使用 EF Core 和 automapper 时遇到了问题。
我的解决方案包含以下层次结构:
BLL <=> DAL <=> EF Core <=> Mysql Database
我在 BLL 中使用 automapper。
并以这个用户类为例:
public class User
{
public Guid Id { get; set; } = Guid.NewGuid();
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid? CreatedById { get; set; }
public Guid? ModifiedById { get; set; }
public virtual User CreatedBy { get; set; }
public virtual User ModifiedBy { get; set; }
}
我有相同的 UserDTO 类(DataTransferObject)。
我在数据库中已经有一个用户创建另一个用户的记录,因为需要填写createdby和modifiedby来创建或更新一个用户。
从数据库中获取用户:
UserDTO userDTO = this._UserBLL.GetUser("Unit", "Test");
//BLL
var mapped = new List<UserDTO>();
this._Mapper.Map(dalResult, mapped); //dalResult = List<User> object
return mapped;
这是一个如何添加用户的示例:
UserDTO testUser2 = new UserDTO
{
FirstName = "Test 2",
LastName = "Test 2",
CreatedBy = userDTO,
ModifiedBy = userDTO
};
this._UserBLL.Add(testUser2);
//BLL
List<User> mappedUsers = new List<User>();
this._Mapper.Map(users, mappedUsers); //users = List<UserDTO> that contains testUser2
DbContext.Users.AddRange(mappedUsers); //Throws exception
DbContext.SaveChanges();
抛出的异常: The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.
但我不知道如何解决异常。 同样的问题是,当我更新现有记录时。
AutoMapping 类是:
this.CreateMap<User, UserDTO>()
.ReverseMap();
你知道如何解决这个问题吗? 我希望你明白我的问题,否则,问我。
国王问候
这里有几个误解
请记住,DTO 是一个愚蠢的类,从某种意义上说,它只是充当信息以强类型方式传播的容器。 当前端向您发送一些数据并且您的后端捕获控制器参数时,您通常会处理 DTO(我知道这不完全正确,只是想在这里说明一点),或者在将 DTO 返回到前端时以任何它需要的理由结束。 那么一般的方法是:
前端发送了一个 DTO
后端控制器捕获
后端服务将 DTO 映射到一些感兴趣的域模型(自动映射器)
后端服务执行业务规则的逻辑步骤,例如在数据库中保存记录或更新我不知道你命名的内容
后端服务将响应(如果有)映射到 DTO(自动映射器)
后端控制器将数据直接发送回前端,以做它需要做的任何事情
现在,关于您的错误,这是实体框架初学者的常见错误。 让我说明发生了什么:
UserDTO userDTO = this._UserBLL.GetUser("Unit", "Test");
//tip: as per the explanation above this should't be a DTO
//EF says "alright!, programmer pull out
//a record from the database and got a object of type UserDTO with Id = "someguid"
//im gonna begin tracking this object to see if it changes in the
//execution of the code.
//In case my fellow programmer wants to modify this object and
//save it in on the database, as I was tracking it down in
//the first place, I'm gonna know how to build my
//SQL statements to perform the right update/delete/create sentence in
//SQL form.
在映射的某个地方,您正在创建具有相同 Id 的相同对象类型,然后实体框架变得疯狂
//EF says: "mmm, that's weird, im tracking the same object
//again, im gonna alert the human. *throws exception*
这里的关键是重新阅读实体框架/核心的文档,以充分了解实体框架的想法现在,关于您的代码和业务需求,您的目标应该是做这样的事情:
//Suppose that the in the controller parameter we receive this DTO
var newUserDto = new UserDto()
{
Firstname = "Rodrigo",
Lastname = "Ramirez",
CreatedBy = 1, //this can be the user Id of the user that sent this DTO
};
var userToCreate = Mapper.Map<User>(newUserDto);
var userCreator = UserRepository.GetById(newUserDto.CreatedBy);
userToCreate.CreatedBy = userCreator;
关于这个话题的最后一句话:
var user = Mapper.Map<User>(newUserDto); //hey mapper, be a pal and transform this newUserDto into a User object.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.