簡體   English   中英

DbContext保存:訪問自定義屬性

[英]DbContext Save: Access Custom Attribute

我為模型的每個屬性定義了自定義屬性

[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)來訪問該屬性,而其他人可以針對每個實體。

您可以使用此LINQ表達式獲取帶有Auditable屬性注釋的sender所有屬性(提供的IsAuditableAuditable屬性的屬性,其中存儲了構造函數的值)

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對象的集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM