加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:46:18 所属栏目:百科 来源:网络整理
导读:我有以下型号: public class Customer{ public int Id {get; set;} public string Name {get; set;} public int AddressId {get; set;} public virtual Address Address {get; set;} public virtual ICollectionCustomerCategory Categories {get; set;}}pu
我有以下型号:
public class Customer
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int AddressId {get; set;}
    public virtual Address Address {get; set;}
    public virtual ICollection<CustomerCategory> Categories {get; set;}
}

public class CustomerCategory
{
    public int Id {get; set;}
    public int CustomerId {get; set;}
    public int CategoryId {get; set;}
    public virtual Category Category {get; set;}
}

public class Address
{
    public int Id {get; set;}
    public string Street{get; set;}
    public virtual PostCode PostCode {get; set;}
}

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

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

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

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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读