Search code examples
c#.netentity-framework-coredomain-driven-design

How to update a property based on Modification of OwnsOne Table in EF Core


I have two classes:

public class Lead 
{
    public Guid Id { get; private set; }
    public EA EA { get; private set; } = new EA();
    public dateTime UpdateDate { get; set; }
}

public class EA 
{
   public string Soldemployee { get; private set; }
}

I follow domain design pattern and EA is value object.

My Entity Framework configuration:

public void Configure(EntityTypeBuilder<Lead> builder)
{
        builder.ToTable("Leads", "Tv");

        #region Properties
        builder.HasKey(x => x.Id);
        builder.OwnsOne(lead => lead.EA,
                eA =>
                {
                    eA.Property(eA => eA.SoldEmployee)
                      .HasColumnName("SoldEmployee")
                      .HasColumnType("nvarchar")
                      .HasMaxLength(256)
                      .IsRequired(false);
                });
}

Now I have this generic code:

private void SetAuditInformation()
{
    Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry[] entities = 
         ChangeTracker.Entries()
                      .Where(x => x.State == EntityState.Added || 
                                  x.State == EntityState.Modified || 
                                  x.State == EntityState.Deleted)
                      .ToArray();

    DateTime currentTime = DateTime.UtcNow; 

    foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry entity in entities)
    {
        if (entity.Entity is IUpdatedAudit updatedAuditEntity)
        {
            // Otherwise set the UpdatedDateUtc
            updatedAuditEntity.UpdatedDateUtc = currentTime;
        }
    }

}

Whenever I update some property of EA. Lead entity ChangeTracker's state is not modified. How to change modify state of Lead entity when property of EA is changed?


Solution

  • private static bool IsValueObjectModified(EntityEntry entity)
    {
         return entity.State == EntityState.Added || entity.State == EntityState.Modified || entity.State == EntityState.Deleted ||
                                entity.References.Any(r => r.TargetEntry != null && r.TargetEntry.Metadata.IsOwned() && IsValueObjectModified(r.TargetEntry));
    }
    

    By using this method it can be tracked