DbContext保存:访问自定义属性

时间:2014-01-30 07:11:56

标签: entity-framework

我为模型的每个属性定制了自定义属性

[Auditable]
public class Student : BaseObject
{
    public Student()
        // Change this parameter to change the DisplayName 
        // (this name is used in all system messages)
        // property of this object
        : base("Student") { }

    public int StudentId { get; set; }

    [Auditable(false)]
    public int OfficeAddressId { get; set; }

保存学生记录时,我想检查可审核属性并将其写入audittrack表。我想在

中这样做
    private void CurrentObjectContext_SavingChanges(object sender, EventArgs e)
    {

有人可以指示我使用Auditable(false)访问该属性,而其他人则可以访问每个实体。

1 个答案:

答案 0 :(得分:2)

您可以使用此LINQ表达式获取sender使用Auditable属性注释的所有属性(提供的IsAuditable属性为Auditable属性,其中值为从构造函数存储)

var auditableProperties = from p in sender.GetType().GetProperties()
    let attribute = p.GetCustomAttributes(typeof(AuditableAttribute), false).SingleOrDefault() as AuditableAttribute
    where attribute != null && attribute.IsAuditable == true
    select p;

表达式的结果是PropertyInfo个对象的集合。