首页 > 解决方案 > 无法检测 EF Core 中阴影属性的更改

问题描述

我正在尝试更改属性,但是阴影属性存在问题,两者CurrentValueOriginalValue为空,是否有阴影属性的替代方法?

var entities = _context
    .ChangeTracker
    .Entries()
    .ToArray();

foreach (var entity in entities)
{
    foreach (var property in entity.Properties)
    {
        if (property.Metadata.IsShadowProperty())
        {
            var newValue = property.CurrentValue;  // null
            var oldValue = property.OriginalValue; // null
        }
    }
}

实体类:

public class ParentEntity
{
    public string Id { get; set; }
    public OwnedEntity SomeEntity { get; set; }
    private string _name;

    public ParentEntity(string id, string name)
    {
        Id = id;
        _name = name;
        SomeEntity = new OwnedEntity();
    }
}

public class OwnedEntity 
{
    public string Id { get; set; }
    public string Name { get; set; }

    public OwnedEntity()
    {
        Id = Guid.NewGuid().ToString();
        Name = "Some Name";
    }
}

配置:

public void Configure(EntityTypeBuilder<ParentEntity> builder)
{
    builder.HasPartitionKey(x => x.PartitionKey);

    builder.Property("_name").ToJsonProperty("name");
    builder.Property(x => x.Id).ToJsonProperty("id");

    builder.OwnsOne(x => x.SomeEntity, x =>
        {
            x.ToJsonProperty("someEntity");
            x.Property(x => x.Id).ToJsonProperty("id");
            x.Property(x => x.Name).ToJsonProperty("name");
        });

    builder.HasKey(x => x.Id);

    builder.HasDiscriminator();

    builder.ToContainer("container1");
}

标签: c#entity-framework-core

解决方案


推荐阅读