简体   繁体   English

实体框架中的存储库模式和查找功能

[英]Repository Pattern and Find Functionality in Entity Framework

It is a good pattern to separate the way objects are persisted from the business logic.将对象持久化的方式与业务逻辑分开是一种很好的模式。 If I expose how objects are persisted in the database to the business logic, then when I change how these objects are persisted, I will have to change the business logic, making them tightly coupled.如果我将对象在数据库中的持久化方式暴露给业务逻辑,那么当我改变这些对象的持久化方式时,我将不得不改变业务逻辑,使它们紧密耦合。

With that being said, suppose that the business logic uses Foo as an object, and suppose that the DAL (using EF) uses FooDbModel as an object for persisting.话虽如此,假设业务逻辑使用 Foo 作为对象,并假设 DAL(使用 EF)使用 FooDbModel 作为对象进行持久化。 Building the CRUD operations with the repository pattern is very simple: Get Foo object, build FooDbModel , do whatever is needed, and build Foo back, and return it.使用存储库模式构建 CRUD 操作非常简单:获取Foo对象,构建FooDbModel ,做任何需要的事情,然后构建Foo并返回它。

But when Find functionality is little more involving.但是,当Find功能涉及更多时。 Ideally, I want to do something like:理想情况下,我想做类似的事情:

Repository.Find(f => f.Name == "something");

where f is of type Foo (not FooDbModel ).其中fFoo类型(不是FooDbModel )。 Is that possible with EF? EF可以吗? I don't want to pass f where if is of type FooDbModel because that is exposing the data persistence to the BL.我不想传递f where if 是FooDbModel类型,因为这FooDbModel数据持久性暴露给 BL。

Is there a trick to do that?有什么技巧可以做到这一点吗?

@IvanStoev solved the problem. @IvanStoev 解决了这个问题。

Basically, I will need to do a select and then a where.基本上,我需要做一个选择,然后一个地方。

To quote him:引用他的话:

Not if you do it on IQueryable.如果您在 IQueryable 上执行此操作,则不会。 Not sure how exactly your methods are structured, but the implementation of the Find method I see is something like context.Set().Select(m => new Foo { ... }).Where(f => ...) which should translate to SQL.不确定您的方法的结构究竟如何,但我看到的 Find 方法的实现类似于 context.Set().Select(m => new Foo { ... }).Where(f => ...)这应该转换为 SQL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM