我试图遍历我的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;
}
}
有谁知道我想要实现的目标是否可行?
1 回答
您应该使用ChangeTracker .