簡體   English   中英

實體框架DbSet反射

[英]Entity Framework DbSet Reflection

我試圖遍歷我的DbContext中包含具有特定基類型的實體的所有DbSet。 我的目標是在我在DbContext上調用SaveChanges並設置一些默認參數之前使用此循環。

在C#中,我的基類看起來像這樣:

public abstract class TrackedEntity
{
    public string ModifiedBy { get; set; }

    public DateTime Modified { get; set; }
}

派生類的一個例子是: -

public class Record : TrackedEntity
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }
}

我在我的DbContext類中創建了一個自定義的SaveChanges方法,並且可以為包含TrackedEntity的每個DbSet獲取一個ProtertyInfo列表,但是當我嘗試遍歷每個DbSet中的值時,我得到一個錯誤,因為我無法投射我的DbSet派生類(例如DbSet <Record>)到基類的DbSet(例如DbSet <TrackedEntity>)。

public class MyContext : DbContext
{
    public DbSet<Record> Records { get; set; }

    public int SaveChanges(string username)
    {
        //Set TrackedEnity update columns
        foreach (PropertyInfo property in GetDbSetPropertyInfos<TrackedEntity>())
        {
            foreach (TrackedEntity entity in (DbSet<TrackedEntity>)property.GetValue(this, null)) //fails here due to cast
            {
                entity.Modified = DateTime.UtcNow;
                entity.ModifiedBy = username;
            }
        }
        return base.SaveChanges();
    }

    //return a list of PropertyInfo for each DbSet with a given type in this context
    IEnumerable<PropertyInfo> GetDbSetPropertyInfos<T>() where T : class
    {
        IEnumerable<PropertyInfo> properties = GetType().GetProperties().Where(p => p.PropertyType.IsGenericType
            && p.PropertyType.Name.StartsWith("DbSet")
            && p.PropertyType.GetGenericArguments().Length > 0
            && p.PropertyType.GetGenericArguments()[0].IsSubclassOf(typeof(T)));

        return properties;
    }
}

有誰知道我想要實現的目標是否可行?

您應該使用ChangeTracker。

....
foreach( var entry in context.ChangeTracker.Entries<TrackedEntity>())
{
    if(entry.State!=EntityState.Unchanged)
    {
        TrackedEntity entity = entry.Entity;
        entity.Modified = DateTime.UtcNow;
        entity.ModifiedBy = username;
    }
}
context.SaveChanges();

暫無
暫無

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

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