我所拥有的:
// 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
我想要的:当拥有的财产(Person
)变为Address
({ {1}})。换句话说,我想将拥有的财产状态传播到父实体级别。这有可能吗?
顺便说一句。我正在使用EF Core v2.1.1。
答案 0 :(得分:3)
您可以使用以下自定义扩展方法:
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