在 EF 中使用预编译的 linq 查询和存储库模式
是否可以在存储库中使用预编译的 linq 查询。目前,我已经设置了存储库,就像
public class CustomerRepository : EntityRepository
{
private readonly IContext _context;
public CustomerRepository(UnitOfWork uow)
{
_context = uow.context;
}
}
我能够通过使用我的实际上下文类 MyEntities :ObjectContext,IContext 按以下方式创建预编译查询。
static Func<ObjectContext, int, Customer> _custByID;
public static Customer GetCustomer( int ID)
{
if (_custByID == null)
{
_custByID = CompiledQuery.Compile<MyEntities, int, Customer>
((ctx, id) => ctx.Customers.Where(c => c.CustomerID == id).Single());
}
return _custByID.Invoke(_context, ID);
}
问题在于 Compile 方法 TArg0 采用从 ObjectContext 派生的类型。由于我将存储库与 IContext 一起使用的全部目的是使用上面的内容隐藏与实体框架相关的代码,这是没有意义的。我应该如何使用预编译的 linq 查询。我应该将它们移至引用我的模型和实体框架的单独的类库,还是我对存储库的理解不正确?我在 ASP.net 应用程序中使用 EF4。
Is it possible to use precompiled linq queries with repositories. Current I have my repositories set up like
public class CustomerRepository : EntityRepository
{
private readonly IContext _context;
public CustomerRepository(UnitOfWork uow)
{
_context = uow.context;
}
}
I would be able to create a precompiled query in the following manner by using my actual context class MyEntities : ObjectContext,IContext.
static Func<ObjectContext, int, Customer> _custByID;
public static Customer GetCustomer( int ID)
{
if (_custByID == null)
{
_custByID = CompiledQuery.Compile<MyEntities, int, Customer>
((ctx, id) => ctx.Customers.Where(c => c.CustomerID == id).Single());
}
return _custByID.Invoke(_context, ID);
}
The problem is that the Compile methods TArg0 takes in a type derived from ObjectContext. Since my whole purpose of using repositories with IContext was to hide entity framework related code using the above doesnt make sense. How should I go about using precompiled linq queries. Should I move them to a separate class library which references my model and the entity framework or is my understanding of the repositories incorrect? I am using EF4 in an ASP.net application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
存储库实现应该具备数据访问技术的知识。存储库的职责是与底层数据源通信以满足契约。如果您无法执行此类优化,那么拥有存储库将毫无用处,因为
ObjectSet
已经是存储库了。在存储库和 EF 之间创建另一层间接层是无用的抽象。The repository implementation should have the knowledge of the data access technology. The responsibility of the repository is to talk to the underlying data source inorder to satisfy the contract. It would be useless to have a repository if you can not perform such optimizations because the
ObjectSet
is already a repository. Creating another layer of indirection between repository and EF is a useless abstraction.