0

大家都好,我有以下類別: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);並忽略這個異常,但讓異常繼續投入審計場景並不是一件好事。它也會影響性能。

任何解決方法,非常感謝。謝謝

回答

1

的問題是,當你在使用導航屬性調用它Property方法只支持基本屬性。

您可以使用ER核心元數據服務,通過EntityEntry.Metadata屬性返回IEntityType。在你的情況下,FindProperty方法,雖然你真的應該放在第一位使用GetProperties,而不是反思:

if (entity.Metadata.FindProperty(prop.Name) == null) 
    continue; 

var p = entity.Property(prop.Name); 
if (p.IsModified) 
    props.Add(new { f = prop.Name, o = p.OriginalValue, c = p.CurrentValue }); 
+0

謝謝。這就是我需要的。通過谷歌和EF文檔網站搜索,它很令人沮喪,文檔沒有提到有關Property方法只支持基本屬性。 –

0

這是因爲entityEntityEntry。你應該正確命名你的變量不感到困惑:

foreach (var entiry in changedEntries) 
{ 
    var entity = entiry.Entity; 
    var entityType = 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) == null) 
       continue; 

      var p = entity.Property(prop.Name); 
      if (p.IsModified) 
       props.Add(new { f = prop.Name, o = p.OriginalValue, c = p.CurrentValue }); 
     } 
    } 
} 
相關問題