本文介绍了实体框架5:使用延迟加载或预先加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉,如果我的问题是正常的。但我满足这个问题,当我使用实体框架5设计我的ASP.NET MVC 4.0应用程序。

I'm sorry if my question is normal. But I meet this problem when I design my ASP.NET MVC 4.0 Application using Entity Framework 5.

如果我选择预先加载,我只是简化使用:

If I choose Eager Loading, I just simplify using :

public Problem getProblemById(int id) {
 using(DBEntity ctx = new DBEntity ())
            {
                return (Problem) ctx.Posts.Find(id);
            }
}

但是,如果使用预先加载,我会遇到的问题:当我想通过其所有属性进行导航,如评论(问题),用户(问题的)......我必须手动使用包括包括这些属性。和在有些时候,如果我不使用这些属性,我会失去性能,也许我失去了实体框架的强度。

But if I use Eager Loading, I will meet problem: when I want to navigate through all its attributes such as comments (of problem), User (of Problem) ... I must manually use Include to include those properties. and At sometimes, If I don't use those properties, I will lost performance, and maybe I lost the strength of Entity Framework.

如果我使用延迟加载。有使用的DbContext 对象有两种方法。第一种方法是使用本地的DbContext对象:

If I use Lazy Loading. There are two ways to use DBContext object. First way is using DBContext object locally :

public Problem getProblemById(int id) {
 DBEntity ctx = new DBEntity ();
 return (Problem) ctx.Posts.Find(id);
}

利用这一点,我想会遇到内存泄漏,因为CTX将永远不会再处理。

Using this, I think will meet memory leak, because ctx will never dispose again.

第二个途径是使的DbContext对象的静态和全球使用它:

Second way is make DBContext object static and use it globally :

static DBEntity ctx = new DBEntity ();
public Problem getProblemById(int id) {
 return (Problem) ctx.Posts.Find(id);
}

我看了一些博客,他们说,如果我用这种方式,我必须控制并发访问(因为多的请求发送到服务器)由我自己,OMG。例如此链接:

I read some blog, they say that, if I use this way, I must control concurrency access (because multi request sends to server) by myself, OMG. For example this link :

那么,如何才能设计出我的应用程序,请帮我找出。

So, how can design my app, please help me figure out.

感谢:)

推荐答案

不要使用静态的DbContext 对象。见c#与实体框架的工作在一个多线程服务器

有关ASP.Net MVC一个简单的规则:使用每个用户请求的的DbContext 实例

A simple rule for ASP.Net MVC: use a DBContext instance per user request.

至于使用延迟加载与否,我要说的这取决于,但我个人停用延迟加载。国际海事组织这是一个的的功能,因为有根本性的问题吧:

As for using lazy loading or not, I would say it depends, but personally I would deactivate lazy-loading. IMO it's a broken feature because there are fundamental issues with it:


  • 实在太难处理异常,因为SQL请求可以在你的code任何一个地方失败 (不只是在DAL因为一个开发人员可以访问在导航属性的任何的一块code的)

  • 表现欠佳如果不能很好使用

  • 太容易写坏了code产生的SQL请求十万

  • just too hard to handle exceptions, because a SQL request can fail at any place in your code (not just in the DAL because one developer can access to a navigation property in any piece of code)
  • poor performances if not well used
  • too easy to write broken code that produces thousands of SQL requests

这篇关于实体框架5:使用延迟加载或预先加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:30