与实体和存储库一起工作 [英] working with entity and repository
问题描述
在这个界面中创建实现db上下文的正确方法是什么?我应该将dbcontext作为参数传递到SQLServerRepository构造函数中,并将类成员dbcontext填充到db中?
public class SQLServerBookRepository:IBookRepository
{
private MyDBContext _db;
public SQLServerRepository(MyDBContext db)
{
_db = db;
}
public void AddBook(Book b){
//将书添加到上下文
_db.SaveChanges();
}
}
我问这是正确的方法吗?有更好的方法吗?我应该将dbcontext存储在与存储库,dao层相同的层中,你该怎么做?
是的,正确的方式是不来做到这一点。作为已经抽象数据库的库的附加层的Repository模式是反模式。
此外,像RavenDB和关系数据库之类的文档数据库的范例是非常不同的。您不会以相同的方式解决/建模您的解决方案。
请参阅此博文 RavenDB和存储库模式,由RavenDB的用户与您的表达有类似的意图,总结自己和Ayende Rahien(又名Oren)之间的讨论Eini),RavenDB的创建者。
关于您创建EF库的相关问题。我的建议是一样的:不要。
实体框架已经为您提供了数据库。它提供了自己的版本的Repository作为 DbSet
和工作单位作为 DbContext
。不要在其上再放一层抽象层:
- 次优,因为现在您无法访问底层的完整API和
- leaky。
let's say that I have some IBookRepository. And besides ravendb I want to add SqlServer implementation of IBookRepository called SQLServerRepository.
What is the proper way to create implemenation of this interface having db context in mind. Should I pass dbcontext as parameter inside SQLServerRepository constructor and populate class member dbcontext to work with db?
public class SQLServerBookRepository : IBookRepository
{
private MyDBContext _db;
public SQLServerRepository(MyDBContext db)
{
_db = db;
}
public void AddBook(Book b){
// adding book to context
_db.SaveChanges();
}
}
I'm asking is this proper way? Is there are better way? Where should I store dbcontext in the same layer with repository, dao layer, how would you do it?
Yes, the proper way is not to do this. The "Repository" pattern as an additional layer over a library that already abstracts the database is an anti-pattern.
Furthermore, the paradigms of a document database like RavenDB and a relational database are very different. You would not solve / model your solutions in the same way.
Refer to this blog post "RavenDB and the Repository pattern", by a user of RavenDB who had similar intentions as you expressed, summarizing a discussion between himself and Ayende Rahien (aka Oren Eini), the creator of RavenDB.
Regarding your follow up "what if" question, related to creating a repository for EF. My advice would be the same: don't.
Entity Framework is already abstracting the database for you. It provides its own versions of a "Repository" as a DbSet
and a "unit of work" as the DbContext
. Don't put another abstraction layer over it that will always be:
- suboptimal because now you can't access the underlying full API and
- leaky.
这篇关于与实体和存储库一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!