如何在 EF 对象上下文CurrentObjectContext_SavingChanges方法中访问 "attribute" 值



我想使用自定义开发的"Auditable"属性来跟踪我的"POCO"对象。必须跟踪具有可审计属性的对象的CRUD操作。为了做到这一点,我覆盖了对象上下文的保存更改方法。但是我不知道如何在保存方法中访问每个实体对象的属性值(是否存在该属性)。任何帮助都将不胜感激。。。

我使用的是EF 6.0。

using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Nido.Common.Utilities.Attributes;
namespace DemoTest.Bll.Models
{
    /// <summary>
    /// Created by MAS IT
    /// </summary>
    [Auditable]
    public class Address : BaseObject
    {
       // Your code here
    }
}

ObjectContext保存方法如下。。

private void CurrentObjectContext_SavingChanges(object sender, EventArgs e)
{
 // if auditable then
 // Tracking code comes here
}

取决于属性类实际上是AuditableAttribute还是只是Auditable

你需要使用System.Linq,然后你可以做任何一件事:

if (sender !=null && 
    sender.GetType().GetCustomAttributes().OfType<AuditableAttribute>().Any())

if (sender !=null && 
    sender.GetType().GetCustomAttributes().OfType<Auditable>().Any())

最新更新