实体框架代码优先包装器还是存储库?
我有时看到有人提到存储库模式是通过 DbSet 和 DbContext 对象内置到实体框架代码优先中的。
然而,这留下了一些问题:
1)注入 - 很难注入,因为没有明确的接口
2)模拟 - 与上面相同
3)对 EnitityFramework.dll 的多个引用 - 假设我在它自己的程序集中创建了我的 Code First /project 然后想在另一个地方引用它,我还必须在没有一些包装器的情况下引用entityFramework.dll
您同意这一点吗?如果您同意,您认为最好的解决方案是什么?
I've seen it mentioned sometimes that Repository Pattern is built into Entity Framework Code First via the DbSet and DbContext objects.
However that leaves a few problems:
1) Injection - Hard to inject as there isn't a clear cut Interface
2) Mocking - Same as above
3) Multiple references to EnitityFramework.dll - Let's say I create my Code First in it's own assembly/project and then want to reference that in another place I also have to reference entityFramework.dll without some wrapper present
Do you aggree with this and what do you think is the best solution if you do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DbSet
具有接口,您通常会实现从DbContext
派生的自己的上下文类,因此它也可以实现您自己的接口,使您能够毫无问题地处理注入。IDbSet
也没有意义,但同时模拟任何公开IQueryable
或接受Expression
的存储库或包装器。 Func<>>
传递给 Linq-to-entities 也没有意义 (这里是简单的示例(原因)。因此,是的,存储库可以处理此问题,但您必须为此付出更多努力,并且您不会使用 Linq 从调用存储库的代码中查询数据库。如果您希望上层使用声明性查询(如使用存储库时的预期),您必须实现自己的规范。DbSet
has interface and you usually implement your own context class derived fromDbContext
so it can also implement your own interface allowing you to deal with injection without any problem.IDbSet
doesn't make sense as well but in the same time mocking any repository or wrapper exposingIQueryable
or acceptingExpression<Func<>>
passed to Linq-to-entities doesn't make sense either (here is simple example why). So yes repository can handle this but you will have to put more effort into this and you will not use Linq to query database from code calling your repository. If you want your upper layer to use declarative queries (as expected when using repository) you must implement your own specifications.