【发布时间】:2013-09-07 01:19:51
【问题描述】:
我有一个使用插件式方法 (Plug-in architecture for ASP.NET MVC) 的应用程序来填充我的 EF 代码优先数据库。在 PreApplicationStartMethod 期间,我从每个插件 (dll) 中提取对象列表以加载到实体框架中。我正在尝试使用这种通用方法(Generic method to insert record into DB),但它说 T 是一个对象,而不是我在插件中指定的特定类型。结果插入失败,因为我的上下文中没有对象数据库集。如果我手动将对象转换为其原始类型,也会发生同样的情况。
IModule.cs(主项目) 公共接口IModule { 列表>实体{获取; } }
Module.cs(插件)
public class Module : IModule
{
public List<List<object>> Entities
{
get
{
List<List<object>> entities = new List<List<object>>();
List<object> renderings = new List<object>();
renderings.Add(new FieldRendering(1, "Text", "String"));
renderings.Add(new FieldRendering(2, "Date", "Date"));
renderings.Add(new FieldRendering(3, "Hidden", "Auto"));
entities.Add(renderings);
return entities;
}
}
}
PreApplicationInit(主项目)
[assembly: System.Web.PreApplicationStartMethod(typeof(Core.Modules.PreApplicationInit), "InitializeModules")]
public class PreApplicationInit
{
private static Context context;
public static void InitializeModules()
{
// code to pull in the modules (works, so suppressing for brevity)
context = new Context();
foreach (List<object> section in module.Entities)
{
foreach (object entity in section)
{
// Inspecting the entity object here indicates the correct type (FieldRendering)
Add(entity);
}
context.SaveChanges();
}
}
private static void Add<T>(T entity) where T : class
{
// Inspecting T here indicates the incorrect type (object)
// Code fails here
context.Set<T>().Add(entity);
}
}
【问题讨论】:
-
谢谢大家,@will 和@aaronbregger 方法的挑战在于
context.Set(entity.GetType())返回的是DbSet 而不是IDbSet。问题是当我尝试检查实体是否已经存在时,我不能使用set.Contains(entity),因为它是特定于 IDbSet 的,当我尝试使用反射来获取标有 key 属性的属性时,我遇到了同样的问题查看类型对象而不是特定类型的反射问题。今晚我会看看@TheEvilPenguin 的做法。
标签: c# asp.net-mvc entity-framework generics