C# 如何使用实体框架5中定义的Attribute.isd?
我正在使用实体框架创建审计跟踪。我想我应该创建一个自定义属性,而不是审计每个属性C# 如何使用实体框架5中定义的Attribute.isd?,c#,entity-framework,asp.net-mvc-4,entity-framework-5,C#,Entity Framework,Asp.net Mvc 4,Entity Framework 5,我正在使用实体框架创建审计跟踪。我想我应该创建一个自定义属性,而不是审计每个属性 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class DoNotAudit : Attribute { } 然后我会把这个应用到我的模型中 [Table("AuditZone")] public class AuditZone { public A
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class DoNotAudit : Attribute
{
}
然后我会把这个应用到我的模型中
[Table("AuditZone")]
public class AuditZone
{
public AuditZone()
{
AuditZoneUploadedCOESDetails = new List<UploadedCOESDetails>();
AuditZonePostcode = new List<Postcodes>();
}
[Key]
public int Id { get; set; }
public string Description { get; set; }
public bool Valid { get; set; }
public DateTime CreatedDate { get; set; }
public int? CreatedBy { get; set; }
[DoNotAudit]
public DateTime? ModifiedDate { get; set; }
public int? ModifiedBy { get; set; }
public virtual UserProfile CreatedByUser { get; set; }
public virtual UserProfile ModifiedByUser { get; set; }
public virtual ICollection<UploadedCOESDetails> AuditZoneUploadedCOESDetails { get; set; }
public virtual ICollection<Postcodes> AuditZonePostcode { get; set; }
}
当我逐步浏览代码时,即使对于modifiedDate属性,它也显示为空。这怎么可能?谢谢你的帮助
感谢您使用以下代码获得的帮助:
dbEntry.Property(propertyName).GetType()
是已修改属性的类型,如DateTime?
对于ModifiedType
。因此,DateTime?
类上没有定义属性。(该属性是在审核区类中定义的)
我要做的是在进入审计代码的修改部分之前保存不应审计的属性列表(至少在循环修改属性列表之前)。然后,在遍历修改的属性时,检查属性名称是否在审计排除的属性列表中。大概是这样的:
var auditExcludedProps = dbEntry.Entity.GetType()
.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(DoNotAudit), false).Any())
.Select(p => p.Name)
.ToList();
foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
{
var doNotAUditDefined = auditExcludedProps.Contains(propertyName);
...
}
您可能需要再次检查dbEntry.Entity.GetType()
是否返回类AuditZone
,并且列表AuditExcludedOps是否包含ModifiedDate
属性
希望有帮助 是的,那会有用的。。但是还有另一个名为dbEntry.member(属性名)的方法,它同样不提供任何信息。。因此,为了明确起见,在属性上使用自定义属性无法检查它?对于ModifiedDate
,这将为您提供一个DbPropertyEntry
对象,请参阅。因此,您将处于与使用dbEntry.Property(propertyName)
时相同的场景中。检查自定义属性的方法是获取类(AuditZone
)的类型,该类使用自定义属性声明属性(ModifiedDate
)。这意味着反射需要开始获取AuditZone的类型信息,然后查看其属性。EF似乎没有提供一种方法来获取属性info
(这将允许您检查自定义属性)给定的DbPropertyEntry
对象。Daniel-我正在设法与您联系,因为我还有一个问题要问您。。但这与这个问题无关。但是链接在这里,丹尼尔-还有一个问题吗?
dbEntry.Property(propertyName).GetType()
var auditExcludedProps = dbEntry.Entity.GetType()
.GetProperties()
.Where(p => p.GetCustomAttributes(typeof(DoNotAudit), false).Any())
.Select(p => p.Name)
.ToList();
foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
{
var doNotAUditDefined = auditExcludedProps.Contains(propertyName);
...
}