.net 如何在EF Core中基于修改OwnsOne表更新属性

j2cgzkjk  于 2023-04-08  发布在  .NET
关注(0)|答案(1)|浏览(138)

我有两个班:

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; }
}

我遵循领域设计模式,EA是价值目标。
我的实体框架配置:

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);
                });
}

现在我有这个通用代码:

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;
        }
    }

}
每当我更新EA的一些属性时,引导实体ChangeTracker的状态没有被修改。当EA的属性被改变时,如何改变Lead实体的修改状态?

hgtggwj0

hgtggwj01#

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));
}

通过使用这种方法可以跟踪

相关问题