实体框架长期数据上下文与短期数据上下文

实体框架长期数据上下文与短期数据上下文

本文介绍了实体框架长期数据上下文与短期数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在以下两个示例之间使用C#和SQL Server(实体框架)的最佳实践是什么:

I would like to know what is the best practice to work with C# and SQL Server (entity framework) between the two examples below :

1-每次您要使用SQL Server时都打开连接,然后立即关闭连接吗?(我使用实体框架使用声明)

1-open connection each time you want to work with SQL server and close it right after ? (I use entity framework using statement)

2-一次打开连接,并在需要执行的所有任务中将其保持打开的时间,即使存在不需要打开SQL连接即可运行的代码?(在这种情况下,我可以自行控制上下文,而无需使用using语句)

2- open connection once and keep it up as long as needed for all the tasks that need to be done even if there is code that doesn't need the SQL connection open to run ? ( I would control the context myself without the using statement in this scenario)

我知道这个问题并不复杂,但是我仍然是数据库和编程领域的新手.

I know this question is not much complicated but I'm still a newbie in the domain of database and programming.

非常感谢您的回答!

推荐答案

尽快打开和关闭.让 ADO.Net 连接池负责最大程度地减少一遍又一遍地实际连接数据库的开销.只要您使用相同的连接字符串,关闭连接实际上就不会关闭它.它只是将其释放回ADO.Net连接池.保持打开状态的时间越长(而不是在池中),池可能需要创建更多的实际连接才能满足数据库请求.

Open and close as quickly as possible. Let ADO.Net connection pooling take care of minimizing overhead of actually connecting to the database over and over. As long as you use the same connection string, closing a connection does not actually close it. It just releases it back to ADO.Net connection pool. The longer you keep it open, (and not in the pool), the more actual connections the pool may need to create to service the database requests.

这篇关于实体框架长期数据上下文与短期数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 06:53