大家都好,我有以下类别:EntityEntry.Property()抛出InvalidOperationException异常
public class EntityA
{
public Guid Id { get; set; }
public string Desc { get; set; }
public EntityB EntityB { get; set; }
}
public class EntityB
{
public Guid Id { get; set; }
public Guid EntityAId { get; set; }
public EntityA EntityA { get; set; }
}
和我有以下运行时代码:
var a1 = new EntityA {Desc = "a1"};
var a2 = new EntityA {Desc = "a2"};
dbx.EntityAs.Add(a1);
dbx.EntityAs.Add(a2);
var b1 = new EntityB { EntityAId = a1.Id };
dbx.EntityBs.Add(b1);
dbx.SaveChanges();
b1.EntityAId = a2.Id;
dbx.SaveChanges();
我在修改我的代码DbContext.SaveChanges()方法,如下所示,试图找到实体中的哪个属性已更改以及其之前和之后的值:
foreach (var entity in changedEntites)
{
var entityType = entity.Entity.GetType();
if (entity.State == EntityState.Modified)
{
var properties = entityType.GetProperties();
var props = new List<object>();
foreach (var prop in properties)
{
if(entityType.GetProperty(prop.Name) == null)
continue;
var pp = entityType.GetProperty(prop.Name);
if(pp.GetValue(entity.Entity) == null)
continue;
var p = entity.Property(prop.Name);
if (p.IsModified)
props.Add(new { f = prop.Name, o = p.OriginalValue, c = p.CurrentValue });
}
}
}
有问题的代码是这一行:
var p = entity.Property(prop.Name);
它抛出InvalidOperationException
:
The property 'EntityA' on entity type 'EntityB' could not be found.
Ensure that the property exists and has been included in the model.
我的问题是,为什么连entityType.GetProperty(prop.Name)
和entityType.GetProperty(prop.Name).GetValue(entity.Entity)
不为空,entity.Property()
依然没能找到的财产?
我可以用一个try-catch块围绕var p = entity.Property(prop.Name);
并忽略这个异常,但让异常继续投入审计场景并不是一件好事。它也会影响性能。
任何解决方法,非常感谢。谢谢
谢谢。这就是我需要的。通过谷歌和EF文档网站搜索,它很令人沮丧,文档没有提到有关Property方法只支持基本属性。 –