mrm*_*mrm 5 c# entity-framework-core
我拥有的:
// 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
Run Code Online (Sandbox Code Playgroud)
我想要的是:Person当拥有的财产 ( Address) 变为Modified( personModified == true)时,能够检测父实体 ( ) 级别的状态更改。换句话说,我想将拥有的财产状态传播到父实体级别。这甚至可能吗?
顺便提一句。我正在使用 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));
}
Run Code Online (Sandbox Code Playgroud)
换句话说,除了检查直接实体进入状态之外,我们还递归地检查每个拥有实体的进入状态。
将其应用于您的样本:
// On Address (owned property) modified:
bool personModified = _dbContext.ChangeTracker
.Entries<Person>()
.Any(x => x.IsModified());
Console.WriteLine(personModified); // -> true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1138 次 |
| 最近记录: |