c# – 如何使用GraphDiff更新相关实体?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用GraphDiff更新相关实体?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下型号:
  1. public class Customer
  2. {
  3. public int Id {get; set;}
  4. public string Name {get; set;}
  5. public int AddressId {get; set;}
  6. public virtual Address Address {get; set;}
  7. public virtual ICollection<CustomerCategory> Categories {get; set;}
  8. }
  9.  
  10. public class CustomerCategory
  11. {
  12. public int Id {get; set;}
  13. public int CustomerId {get; set;}
  14. public int CategoryId {get; set;}
  15. public virtual Category Category {get; set;}
  16. }
  17.  
  18. public class Address
  19. {
  20. public int Id {get; set;}
  21. public string Street{get; set;}
  22. public virtual PostCode PostCode {get; set;}
  23. }

从上面,并使用GraphDiff,我想更新客户聚合如下:

  1. dbContext.UpdateGraph<Customer>(entity,map => map.AssociatedEntity(x => x.Address)
  2. .OwnedCollection(x => x.Categories,with => with.AssociatedEntity(x => x.Category)));

但上面没有更新任何东西!!

在这种情况下使用GraphDiff的正确方法是什么?

解决方法

GraphDiff基本上区分了两种关系:拥有和关联.
拥有可以被解释为“成为”的一部分,意味着拥有的任何东西都将与其所有者一起插入/更新/删除.
GraphDiff处理的另一种关系是关联的,这意味着在更新图形时,GraphDiff只会更改与关联实体本身的关系,而不会更改关联实体本身的关系.
当您使用AssociatedEntity方法时,子实体的State不是聚合的一部分,换句话说,您对子实体所做的更改将不会保存,只会更新父navegation属性.
如果要保存对子实体的更改,请使用OwnedEntity方法,因此,我建议您尝试这样做:
  1. dbContext.UpdateGraph<Customer>(entity,map => map.OwnedEntity(x => x.Address)
  2. .OwnedCollection(x => x.Categories,with => with.OwnedEntity(x => x.Category)));
  3. dbContext.SaveChanges();

猜你在找的C#相关文章