【发布时间】:2013-12-10 16:43:52
【问题描述】:
我正在使用 EF6 ObjectContext 生成器,这意味着我们的实体继承自 EntityObject。
我正在尝试为简单的 CRUD 操作实现一个通用存储库,但在派生实体方面我遇到了一个特定问题。尽管进行了许多不同的尝试,但我无法获得正确的代码来处理这个问题!
public DataRepository(ObjectContext context)
{
_context = context;
_objectSet = _context.CreateObjectSet<T>();
Type baseType = GetBaseEntityType();
if (baseType == typeof(T))
_objectSet = _context.CreateObjectSet<T>();
else
// how to create the objectset here?
// I have tried the below but it blows up at runtime with an invalid cast exception
_objectSet = (IObjectSet<T>)Activator.CreateInstance(typeof(ObjectSetProxy<,>).MakeGenericType(typeof(T), baseType), context);
}
我已经看完了
Entity Framework: ObjectSet and its (generics) variance
但这似乎是针对获取 ObjectQuery 而不是 ObjectContext。非常感谢任何帮助。 :o)
更新:如果没有任何干净的解决方案,人们可以想到任何解决方法吗?我考虑了一个自动生成的派生实体列表,并检查类型等,但由于它是一个通用存储库,它最终必须使用 IObjectSet,因此以下行无论如何都会失败,并且无效转换 _objectSet = (IObjectSet) _context.CreateObjectSet();
【问题讨论】:
标签: c# entity-framework generics objectcontext