简体   繁体   English

如何使用AutoMapper更新具有嵌套实体的实体,并使用实体框架保存更新的实体?

[英]How do I update an entity with nested entities with AutoMapper and save the updated Entity with Entity Framework?

I've created a mapping to map a collection in the ViewModel to another collection on a Model which seems to work without a problem. 我创建了一个映射,将ViewModel中的集合映射到Model上的另一个集合,该集合似乎没有问题。 After mapping, The child object of the Model has the appropriate updates. 映射之后,Model的子对象具有适当的更新。

configuration.CreateMap<SourceViewModel, Destination>()                
            .ForMember(d => d.ChildOfDestination, 
                      opt => opt.MapFrom(s => Mapper.Map<ICollection<SourceViewModel>, ICollection<Destination>>(s.ChildOfSource)));

However, on save an error is thrown: 但是,在保存时会抛出错误:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. 操作失败:无法更改关系,因为一个或多个外键属性不可为空。 When a change is made to a relationship, the related foreign-key property is set to a null value. 当对关系进行更改时,相关的外键属性将设置为空值。 If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted. 如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

What I have found is ChangeTracker.Entries() has extra items with a state of "Added". 我发现ChangeTracker.Entries()有额外的项目状态为“已添加”。 For example, my Model.ChildCollection has a count of 2, but in Entries(), I have the original 2 items from ChildCollection with states of "Modified", and 2 of the same items with States of "Added" 例如,我的Model.ChildCollection的计数为2,但在Entries()中,我有来自ChildCollection的原始2项,状态为“Modified”,而2个相同项目的状态为“Added”

public async Task<IHttpActionResult> Update([FromBody] SourceViewModel viewModel) {
    var model = await _repository.GetByIdAsync(viewModel.Id);
    Mapper.Map(viewModel, model);
    _repository.Update(model);
    await _unitOfWork.SaveAsync();
}

I wrote some code to get around the problem for the time being but it's a hack to a bigger problem that I'm not sure how to solve. 我写了一些代码来暂时解决问题,但这是一个更大问题的黑客,我不知道如何解决。

foreach (var child in ViewModel.Child)
{
  var record = Model.Child.SingleOrDefault(c => c.ID == child.ID);

  if (record != null)
      Mapper.Map(child, record);
  else
      Model.Child.Add(Mapper.Map<SourceViewModel, Destination>(child));
}

Entity Framework 6 实体框架6

Disconnected data is an old problem that precedes Entity Framework and, for that matter, most data access tools. 断开连接的数据是一个老问题,在实体框架之前,就此而言,大多数数据访问工具。 It's never been an easy one to solve. 这从来都不是一个容易解决的问题。 The server sends data down the wire, not knowing what may happen to it in the client app that requested it, not even knowing if it will return. 服务器通过网络发送数据,不知道在请求它的客户端应用程序中可能发生什么,甚至不知道它是否会返回。 Then, suddenly, some data reappears in a request. 然后,突然,一些数据再次出现在请求中。 But is it the same data? 但这是相同的数据吗? What was it up to in its absence? 在缺席的情况下该怎么办? Did anything happen to it? 发生了什么事吗? Is it completely new data? 这是全新的数据吗? So much to worry about! 非常值得担心!

Source: https://msdn.microsoft.com/da-dk/magazine/mt694083 资料来源: https//msdn.microsoft.com/da-dk/magazine/mt694083

A very good response on this site referring to the article above: https://stackoverflow.com/a/21436713/550198 在本网站上的一个非常好的回应,参考上面的文章: https//stackoverflow.com/a/21436713/550198

Entity Framework Core / Entity Framework 7 实体框架核心/实体框架7

Entity Framework Core also known as EF7 has new features that will allow you to walk the object graph. 实体框架核心(也称为EF7)具有允许您遍历对象图形的新功能。 eg 例如

context.ChangeTracker.TrackGraph(someEntity,  e => e.Entry.State = EntityState.Added);

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

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