4
我想循環遍歷包含具有某種基本類型的實體的DbContext中的所有DbSets。我的目標是在我調用DbContext上的SaveChanges之前使用這個循環,並設置一些默認參數。實體框架DbSet反射
在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 < T rackedEntity>)。
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;
}
}
有誰知道我是否試圖實現是可能的?
完美,謝謝! – user1573618