简体   繁体   English

实体框架上下文?

[英]Entity Framework Context?

I am really having a hard time trying to figure out where the EF Context is managed in an MVC app. 我真的很难弄清楚在MVC应用程序中EF上下文的管理位置。

I am using the Service/Repository/EF approach and was playing with the UnitOfWork pattern with a context inside of it, and then using it inside the controller actions to utilize various services. 我正在使用Service / Repository / EF方法,并在其中包含上下文的情况下使用UnitOfWork模式,然后在控制器操作中使用它来利用各种服务。 It works, but by doing this, I am making the controllers dependent on EF right? 它可以工作,但是通过这样做,我使控制器依赖于EF,对吗?

Any suggestions? 有什么建议么?

If you rely upon abstractions and create an IUnitOfWork and IRepository encapsulating the EF Context the Controller would be dependent on the abstractions and not any concrete implementation. 如果您依赖抽象并创建一个封装EF上下文的IUnitOfWork和IRepository,则Controller将依赖于抽象而不是任何具体的实现。

The repository and unit of work themselves are the only classes that would be dependent on Entity Framework or whatever ORM you are using. 存储库和工作单元本身是唯一依赖于Entity Framework或您使用的任何ORM的类。

public class MyController : Controller
{
  public MyController(IRepository r1, IRepository r2, IUnitOfWork uow)
  { ... }

  [HttpPost]
  public ActionResult SomeAction(Model data)
  {
    _r1.DoSomeChangesToEntities(data);
    _r2.DoSomeChangesToEntities(data);
    _uow.SaveChanges();
    return View(...);
  }
}

Edit as per request: 根据要求编辑:

A simple Unit Of Work implementation could be: 一个简单的工作单元实现可以是:

public class EFUnitOfWork : IUnitOfWork
{
  private DataContext _context;

  public EFUnitOfWork(DataContext context)
  {
    _context = context;
  }

  public void Commit()
  {
    _context.SubmitChanges();
  } 
}

You would of course make sure that your services/repositories use the same context as the Unit of Work by injecting the same context into them. 您当然可以通过向服务/存储库注入相同的上下文来确保它们使用与工作单元相同的上下文。

That depends on what you meant "making controller dependent on EF"? 那取决于您的意思是“使控制器依赖EF”?

Do you use any EF related class in controllers? 您是否在控制器中使用了任何与EF相关的类? If not they are obviously not dependent on EF and you can easily swap your repositories and unit of work for other implementation (for example using NHibernate). 如果不是这样,则它们显然不依赖于EF,您可以轻松地将存储库和工作单元交换为其他实现(例如,使用NHibernate)。

But yes whole your asp.net mvc application is dependent on EF if you are using it in any layer - it will simply not run without loading EF dlls. 但是,是的,如果您在任何层中使用它,整个asp.net mvc应用程序都依赖于EF-如果不加载EF dll,它将无法运行。

http://efmvc.codeplex.com/上查看示例代码

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

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