2017-10-04 134 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 
} 

即使只有一个类需要这种行为,我仍然会使用该接口,因为它使得您的代码不言自明。