c# - EntityFramework 避免打开/关闭连接?

标签 c# .net entity-framework

在使用这样的代码时,有什么简单的方法可以避免打开和关闭连接:

using (Entities context = new Entities())
                {
                    returnValue = context.ExecuteStoreCommand(sqlStr, param1, param2, param3, param4, param5, param6, param7);
                    context.SaveChanges();
                    return returnValue;
                }

我在需要在大型数据库(MySQL 更新)中运行的不同方法中有很多这样的代码。如果它不打开/关闭每个方法之间的连接(使用/SaveChanges),它会运行得更快。

也许我必须完全更改代码并将上下文作为静态成员放置,然后从所有方法中删除 using?或者有没有简单的设置?

最佳答案

您应该使用工作单元模式。通过使用工作单元模式,您可以创建对数据库的事务调用。

unit of work pattern

关于c# - EntityFramework 避免打开/关闭连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14292649/

相关文章:

.net - Windows Service System.Timers.Timer无法启动

c# - 将嵌套对象保存到 .Net 中的 Realm 数据库

c# - 在 ASP.NET 5 WebAPI 中使用 OData 时如何获取分页信息和单个记录

c# - 检查属性是否可以延迟加载/是否可用而无需捕获异常

c# - 具有多个 ColorAnimations 的 Silverlight Storyboard

c# - EF : Include navigation property and exclude sub navigation property in same time

c# - 无法将 lambda 表达式转换为类型 'ServiceLifetime',因为它不是 Asp.net core 2.2 上的委托(delegate)类型

c# - .Net Mvc 4 中自己写账号注册方法的几个问题

c# - 如何从命令行使用 msbuild 编译我的 C# 解决方案

c# - 在 JsonConvert.SerializeObject 中自定义标识参数