【问题标题】:Getting property value of a class that belongs to another class获取属于另一个类的类的属性值
【发布时间】:2018-03-15 19:42:35
【问题描述】:

我有类似这样的课程:

  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;}

    }

我有一些审核设置,如果我更新 Foo,那么我可以获得除“Bar”之外的所有属性的属性名称和值。有没有办法获取“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。

【问题讨论】:

  • 如果 BarProp1 被修改,它已经被报告了,因为 Bar 也是 Modified
  • 无栏未修改。只有 foo 属性已被修改但我想获取 bar 属性的值,因为我想为其他目的审核 Bar 属性值。
  • 然后定义一个接口,该接口规定了一个(未映射的)计算属性,其中包含用于审计的附加信息。
  • 我是 C# 新手,请您简单解释一下。所以我可以创建一个接口,我的 foo 类将从那里继承,在审计中我可以检查我的 foo 类是 ISomeInterface 然后我可以执行一些逻辑。但是我应该在接口中添加什么。

标签: c# entity-framework c#-4.0 audit


【解决方案1】:

您希望类向您的审计系统报告其他信息。我认为最好的方法是在您的 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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2021-05-13
    • 2010-10-03
    • 2021-04-02
    相关资源
    最近更新 更多