EF Core owned property state propagation to parent entity

c# entity-framework-core

Question

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.

1
3
7/19/2018 9:39:13 AM

Accepted Answer

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 
5
7/19/2018 10:59:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow