繁体   English   中英

EF核心拥有的财产状态传播到上级实体

[英]EF Core owned property state propagation to parent entity

我有的:

// Parent entity
public class Person
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    public Address Address { get; set; }
}

// Owned Type
public class Address {
    public string Street { get; set; }
    public string Number { get; set; }
}

...

// Configuration
public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> builder)
    {
        builder.OwnsOne(person => person.Address);
    }
}

...

// On Address (owned property) modified:
bool personModified = _dbContext.ChangeTracker
    .Entries<Person>()
    .Any(x => x.State == EntityState.Modified);

Console.WriteLine(personModified);  // -> false 

我想要的是:当拥有的属性( Address )被ModifiedpersonModified == true )时,能够检测父实体( Person )级别的状态变化。 换句话说,我想将拥有的财产状态传播到父实体级别。 这有可能吗?

顺便说一句。 我正在使用EF Core v2.1.1。

您可以使用以下自定义扩展方法:

public static class Extensions
{
    public static bool IsModified(this EntityEntry entry) =>
        entry.State == EntityState.Modified ||
        entry.References.Any(r => r.TargetEntry != null && r.TargetEntry.Metadata.IsOwned() && IsModified(r.TargetEntry));
}

换句话说,除了检查直接实体的进入状态外,我们还递归检查每个拥有实体的进入状态。

将其应用于样本:

// On Address (owned property) modified:
bool personModified = _dbContext.ChangeTracker
    .Entries<Person>()
    .Any(x => x.IsModified());

Console.WriteLine(personModified);  // -> true 

暂无
暂无

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

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