我正在尝试更新实体的 IEnumerable
属性,并使用AutoMapper将新对象添加到其中 . 我收到以下错误:
无法跟踪实体类型“Child”的实例,因为已经跟踪了另一个具有{'Id'}键值的实例 .
基本上,我从这个实例开始:
// Crean ate original instance
var instance = new Parent
{
Children = new List<Child>
{
new Child
{
Value = "X1"
}
}
};
// Add instance to DbContext
context.Parents.Add(instance);
// Save changes
context.SaveChanges();
// Try to get the instance back
var entity = context.Parents.First();
// Serialize and de-serialize the instance to simulate an object being sent from API layer
var updatedInstance = JsonConvert.DeserializeObject<Parent>(JsonConvert.SerializeObject(entity));
// Create a new child object
var newChild = new Child
{
Value = "X2"
};
// Add the child to the API generated object
updatedInstance.Children.Add(newChild);
// Beging tracking for changes to entity
context.Update(entity);
// Apply changes from updatedInstance back to entity
mapper.Map(updatedInstance, entity);
// Save changes but I get Error here!
context.SaveChanges();
我的模型和数据库上下文:
public class Parent
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Value { get; set; }
}
public sealed class EntityDbContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
}
我甚至尝试使用 UseDestinationValue
的AutoMapper但没有成功:
internal class ParentProfile : Profile
{
public ParentProfile()
{
CreateMap<Parent, Parent>()
.ForMember(x => x.Children, opt => opt.UseDestinationValue())
.ReverseMap();
}
}
internal class ChildProfile : Profile
{
public ChildProfile()
{
CreateMap<Child, Child>()
.ReverseMap();
}
}
This is the link of the repo with all the code.
我感谢任何帮助或提示 . 我只是想了解正确使用AutoMapper和EntityFramework而不是manny更新所有属性 . 谢谢 .