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

标签 c# entity-framework ef-code-first graphdiff

我有以下模型:

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 基本上区分了两种关系:ownedassociated

Owned 可以解释为“成为...的一部分”,这意味着拥有的任何东西都将与其所有者一起插入/更新/删除。

GraphDiff 处理的另一种关系是关联的,这意味着在更新图形时,GraphDiff 只更改关联实体本身的关系,而不是关联实体本身。

当您使用AssociatedEntity 方法时,子实体的状态不是聚合的一部分,换句话说,您对子实体所做的更改不会被保存,只是它会更新父导航属性。

如果您想保存对子实体的更改,请使用OwnedEntity 方法,因此,我建议您试试这个:

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

关于c# - 如何使用 GraphDiff 更新相关实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28341027/

相关文章:

c# - Entity Framework 代码优先 : Using a database that doesn't need to be separately installed?

c# - GetRequestStream() 返回 WebException 超时......但仅在某些机器上

方法的 C# 字符串表示

c# - 如何在 Entity Framework 6 中混合使用 TPH 和 TPT?

c# - 通过 Entity Framework 连接的多方进行排序

c# - EF 中的 DbContext 是否应该具有较短的生命周期?

azure - MS Azure/代码优先 : Login failed for user

c# - Windows 桌面搜索不返回 QueryFocusedSummary

c# - 如何将 CloudFX 与 Azure SDK 2.0 结合使用?

c# - 使用 Sub Select 而不是 INNER JOIN 的 Entity Framework