与实体和存储库一起工作 [英] working with entity and repository

查看:103
本文介绍了与实体和存储库一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些IBookRepository。除了ravendb,我想添加名为SQLServerRepository的IBookRepository的SqlServer实现。



在这个界面中创建实现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 。不要在其上再放一层抽象层:


  1. 次优,因为现在您无法访问底层的完整API和

  2. 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:

  1. suboptimal because now you can't access the underlying full API and
  2. leaky.

这篇关于与实体和存储库一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆