Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core owned property state propagation to parent entity

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.

like image 271
mrm Avatar asked Jul 19 '18 07:07

mrm


Video Answer


1 Answers

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 
like image 92
Ivan Stoev Avatar answered Sep 20 '22 12:09

Ivan Stoev