C# 更好的定义上下文对象的方法
我希望每次都使用实体框架上下文对象。 在asp.net中定义的更好方法是什么 例:C# 更好的定义上下文对象的方法,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,我希望每次都使用实体框架上下文对象。 在asp.net中定义的更好方法是什么 例: 我希望在任何地方都使用此上下文,而不必使用重复使用,虽然您可以这样做,但microsoft建议您以不同的方式使用上下文,请查看: 另外,请看一下这个相关的线程:如果您只是想使用一些语法来避免使用而每次都创建一个新的上下文,那么您可以编写一些扩展方法来帮助您编写如下代码: // Execute is the extension method which takes the code // in the using
我希望在任何地方都使用此上下文,而不必使用重复使用
,虽然您可以这样做,但microsoft建议您以不同的方式使用上下文,请查看:
另外,请看一下这个相关的线程:如果您只是想使用一些语法来避免使用而每次都创建一个新的上下文,那么您可以编写一些扩展方法来帮助您编写如下代码:
// Execute is the extension method which takes the code
// in the using block as a delegate
SomeEntities.Execute(context =>
context.SomeTable.Where(item => item.Ammount > 100));
如果你想要的话,我可以和你分享代码。如果您想始终使用单个上下文,请参考CloudyMarble的答案。相关:请定义everywhere?班级里到处都是?在你的整个项目中?
...
The lifetime of the ObjectContext begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use using if you want all the resources that the context controls to be disposed at the end of the block. When you use using, the compiler creates a try/finally block and calls dispose in the finally block. Here are some general guidelines when deciding on the lifetime of the object context:
1. When working with long-running object context consider the following:
- As you load more objects and their references into memory, the object
context may grow quickly in memory consumption. This may cause
performance issues.
- Remember to dispose of the context when it is no longer required.
- If an exception caused the object context to be in an unrecoverable
state, the whole application may terminate.
- The chances of running into concurrency-related issues increase as
the gap between the time when the data is queried and updated grows.
2. When working with Web applications, **use an object context instance per request**...
3. When working with Windows Presentation Foundation (WPF) or Windows Forms, use an object context instance per form. This lets you use change tracking functionality that object context provides.
...
// Execute is the extension method which takes the code
// in the using block as a delegate
SomeEntities.Execute(context =>
context.SomeTable.Where(item => item.Ammount > 100));