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