当我使用AutoMapper时,出现了以下错误:
“Attaching an entity of type 'MyProject.DAL.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.”
我想要在从数据库中检索User后将其映射到UserModel。我在UI中更改UserModel属性,然后再次将其映射到User并进行更新。
我的代码如下:
但是如果我不使用自动映射器,而是像下面的代码一样编写,它可以正常工作。
“Attaching an entity of type 'MyProject.DAL.User' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.”
我想要在从数据库中检索User后将其映射到UserModel。我在UI中更改UserModel属性,然后再次将其映射到User并进行更新。
我的代码如下:
public UserModel GetUserByUserId(int id)
{
var user = db.Users.Where(p => p.UserId == id).FirstOrDefault();
var userModel = Mapper.Map<UserModel>(user);
return userModel;
}
public void Update(UserModel userModel)
{
var user = Mapper.Map<User>(userModel);
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
}
但是如果我不使用自动映射器,而是像下面的代码一样编写,它可以正常工作。
public void Update(UserModel userModel)
{
updatingUser.Email = userModel.Email;
updatingUser.FirstName = userModel.FirstName;
updatingUser.ModifiedDate = DateTime.Now;
updatingUser.LastName = userModel.LastName;
updatingUser.Password = userModel.Password;
updatingUser.UserName = userModel.UserName;
db.Entry(updatingUser).State = EntityState.Modified;
db.SaveChanges();
}
我该怎么做: