我正在使用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();
答案 0 :(得分:0)
This可能会引起人们的兴趣。我不知道版本6中的行为是否已更改。
答案 1 :(得分:0)
我自己最终整理了这个。传入基础和派生实体(我们只有一个级别的继承)。以下是其他人需要指针时的外观风格......
public class DataRepository:IRepository 其中TBaseEntity:EntityObject 其中TDerivedEntity:TBaseEntity { protected static Ent ctx {get {return DBContextManager.GetDBContext();}}
private ObjectContext _context;
private readonly ObjectSet<TBaseEntity> _objectSet;
public DataRepository(): this(DBContextManager.GetDBContext()){}
public DataRepository(ObjectContext context)
{
_context = context;
_objectSet = _context.CreateObjectSet<TBaseEntity>();
}
private ObjectQuery<TDerivedEntity> TypedObjectSet
{
get
{
return _objectSet.OfType<TDerivedEntity>();
}
}
public IEnumerable<TDerivedEntity> Find(Expression<Func<TDerivedEntity, bool>> predicate)
{
return TypedObjectSet.Where(predicate);
}
public TDerivedEntity Single(Func<TDerivedEntity, bool> predicate)
{
return TypedObjectSet.Single(predicate);
}
// etc etc