实体框架和MVC在业务层和数据访问层建立的DbContext [英] Entity Framework and MVC create DbContext in business layer or data access layer

查看:216
本文介绍了实体框架和MVC在业务层和数据访问层建立的DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来实体框架和.NET和正在致力于建设一个MVC 4应用程序。我觉得我有点困惑应在其中创建我的数据库上下文实例。在我的应用程序,我有几个层次:网络,业务,数据访问,数据库(这些都是每个单独的项目)。在数据访问层,我有每个表一个类。一个例子,我看到显示了创建数据访问层内的每个方法内的上下文(我可能误解了它)。更新多个表的业务逻辑的一部分时,这似乎不是很实用。这似乎创建每个数据访问层方法中一个新的上下文的结果是这样的错误:实体对象不能被IEntityChangeTracker的多个实例引用更新多个表时

I am new to Entity Framework and .NET and am working on building an MVC 4 application. I think I'm a little confused about where my database context instances should be created. In my application, I have several layers: Web, Business, Data Access, Database (these are each separate projects). In the data access layer, I have one class per table. An example I saw shows creating the context inside each method inside the data access layer (I may have misunderstood it). This doesn't seem very practical when updating multiple tables as part of the business logic. It seems the result of creating a new context inside each data access layer method is this error: An entity object cannot be referenced by multiple instances of IEntityChangeTracker when updating multiple tables.

因此​​,它是可以接受建立在业务层方法的上下文,然后传递到数据访问层的方法呢?还是有更好的方式来做到这一点?

So is it acceptable to create the context in the business layer method and then pass that to the data access layer methods? Or is there a better way to do it?

像这样在上下文来自于业务层:

Something like this where the context comes from the business layer:

public User RetrieveUserById(int id, MyDbContext ctx)
    {            
        User findUser = ctx.Users.Find(id);
        return findUser;
    }

而不是创建数据访问层方法中的背景:

instead of creating the context inside the data access layer method:

public User RetrieveUserById(int id)
    {
        var ctx = new MyDbContext();
        User findUser = ctx.Users.Find(id);
        return findUser;
    }

我AP preciate的帮助!

I appreciate the help!

推荐答案

数据访问层。创建与所述的DbContext一起存在于数据层的工作组级。
尝试搜索的工作格局Asp.net单位。

Data access layer. Create a "Unit of work" class which exists in the data layer together with the DbContext. Try searching for "Asp.net unit of work pattern".

<一个href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application\" rel=\"nofollow\">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application1

基本上,它是一个集中的地方,召集多个仓库/桌,这样就可以在多个存储库行为不设置你的背景。你不必如图准确使用它。您可以修改它来满足您的需求。

Basically, it is a central place to bring together multiple repositories/tables, so that you can act on multiple repositories without disposing your context. You don't have to use it exactly as shown. You can modify it to fit your needs.

这篇关于实体框架和MVC在业务层和数据访问层建立的DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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