2017-10-04 136 views
0

我上課是這樣的:獲得屬性值屬於其他類

public class foo{ 

     public string FooProp1 {get; set;} 

     public Bar Bar{get; set;} 

    } 

public class Bar{ 

     public string BarProp1 {get; set;} 

     public string BarProp2 {get; set;} 

    } 

我有一些審計設置,其中如果我更新美孚話,我可以得到的屬性名稱和值的所有財產除了'酒吧'。有沒有辦法獲得'BarProp1'的屬性名稱和值。

private void ProcessModifiedEntries(Guid transactionId) { 
    foreach (DbEntityEntry entry in ChangeTracker.Entries().Where(t => t.State == EntityState.Modified).ToList()) { 
     Track audit = CreateAudit(entry, transactionId, "U"); 

     foreach (var propertyName in entry.CurrentValues.PropertyNames) { 

       string newValue = entry.CurrentValues[propertyName]?.ToString(); 
       string originalValue = entry.OriginalValues[propertyName]?.ToString();     
       SetAuditProperty(entry, propertyName, originalValue, audit, newValue);    
     } 
    } 
    } 

我想在Foo發生變化時審覈BarProp1。

+0

如果'BarProp1'被修改了,它將會被報告,因爲'Bar'也是'Modified'。 –

+0

沒有欄未修改。只有foo屬性已被修改但我想獲得bar屬性的值,因爲我想爲其他用途的Audit Bar屬性值。 –

+0

然後定義一個接口,該接口規定包含用於審計的其他信息的(未映射的)計算屬性。 –

回答

0

您希望課程向您的審計系統報告其他信息。我認爲最好的地方是你的CreateAudit方法。問題是如何。

可能在那裏的代碼,做一些特別的東西對每個到來的entry

var foo = entry.Entity as Foo; 
if (foo != null) 
{ 
    // do something with foo.Bar 
} 

var boo = entry.Entity as Boo; 
if (boo != null) 
{ 
    // do something with boo.Far 
} 

當然,這是不是很漂亮。

如果您有需要報告給審計人員的其他信息,我會定義一個接口和粘性,以每個類的多個類:

public interface IAuditable 
{ 
    string AuditInfo { get; } 
} 

public class Foo : IAuditable 
{ 
    public string FooProp1 { get; set; } 
    public Bar Bar { get; set; } 

    [NotMapped] 
    public string AuditInfo 
    { 
     get { return Bar?.BarProp1; } 
    } 
} 

然後在CreateAudit

var auditable = entry.Entity as IAuditable; 
if (auditable != null) 
{ 
    // do something with auditable.AuditInfo 
} 

即使只有一個類需要這種行爲,我仍然會使用該接口,因爲它使得您的代碼不言自明。