What I have:
// 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
What I want: to be able to detect State changes on parent entity (Person
) level when owned property (Address
) become Modified
(personModified == true
). In other words, I want to propagate owned property state to parent entity level. Is this even possible?
Btw. I'm using EF Core v2.1.1.
You can use the following custom extension method:
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));
}
In other words, additionally to checking the direct entity entry state we check recursively the entry states for each owned entities.
Applying it to your sample:
// On Address (owned property) modified:
bool personModified = _dbContext.ChangeTracker
.Entries<Person>()
.Any(x => x.IsModified());
Console.WriteLine(personModified); // -> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With