我正试图循环遍历DbContext中包含特定基础类型实体的所有DbSet。我的目标是在调用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中的值时,我会收到错误提示,因为我无法将派生类(e.g. DbSet< Record >)的DbSet强制转换为基类(e.g. DbSet< TrackedEntity >)的DbSet。
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;
}
}
有人知道我想实现的是否可行吗?
.Where(e => e.State!= EntityState.Unchanged)
- Flimtix