c# – 使用实体框架而不使用语句的缺点?

c# – 使用实体框架而不使用语句的缺点?,第1张

概述有很多像这样的代码块: public class SomeController : Controller{ DbEntities entity = new DbEntities(); public ActionResult Add() { entity.someOperations... return View(); } 有很多像这样的代码块:

public class SomeController : Controller{    DbEntitIEs entity = new DbEntitIEs();    public ActionResult Add()    {        entity.someOperations...        return VIEw();    }    public ActionResult Edit()    {        entity.someOperations...        return VIEw();    }    public ActionResult Detail()    {        entity.someOperations...        return VIEw();    }    public ActionResult Detail()    {        entity.someOperations...        return VIEw();    }    .....

我应该改变这样的方法吗?:

public class SomeController : Controller{    public ActionResult Add()    {        using(DbEntitIEs entity = new DbEntitIEs())        {            entity.someOperations...        }        return VIEw();    }    .....

在EF中不使用using语句有什么问题?或者最好的方法是什么?另外,如果我们使用using语句代码块也会增长.

谢谢…

解决方法 使用声明方法是您在上面提出的两种方法中最好的.使用这种方法,可以确保ObjectContext在使用后关闭并处理掉.

使用您的其他方法,可以假设ObjectContext可以保持未闭合,从而占用与数据库的连接.要查看此 *** 作,请尝试使用其他方法创建示例应用程序,然后使用EFProfiler对其进行概要分析并观察ObjectContext打开的数量,同时关闭的数量将明显减少.

我最近参与了一个项目,该项目在高使用率下遇到了数据库问题,采用了你的第二种模式(你可以看到我的问题HERE).由于我没有足够的时间在项目/代码库上太大,我没有选择切换到using语句方法.相反,我实现了以下 *** 作来手动强制在Global.asax中的End_Request上处理ObjectContext(我在我的BusinessLayerService的静态实例上有一个DbContext的实例:

protected voID Application_EndRequest(object sender,EventArgs e)    {        BusinessLayerService.Instance.dispose();        BusinessLayerService.Instance = null;    }

但是,如果您从项目开始有选项:我强烈建议使用使用模式

总结

以上是内存溢出为你收集整理的c# – 使用实体框架而不使用语句的缺点?全部内容,希望文章能够帮你解决c# – 使用实体框架而不使用语句的缺点?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1217918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存