跨多个方法调用共享相同的DataServiceContext-好还是不好?
作者:互联网
我想知道应如何使用DataServiceContext实例的标准实践.如果我有一个包含多个方法的类,需要在该上下文上执行操作,那么我应该在每个方法内创建一个新的上下文实例,还是让该上下文成为该类的单个成员,并由所有方法共享?
我之所以这么问,是因为我最近看到另一位开发人员在我正在处理的某些代码中发表了评论,其中提到需要在添加一些对象之后并对其执行更多操作之前重新创建上下文.
即我应该这样做:
public class ServiceHelper
{
public void DoSomething()
{
DataContext ctx = new DataContext(Uri);
//do something with the context and call SaveChanges()
}
public int GetSometing()
{
DataContext ctx = new DataContext(Uri);
return ctx.GetSomething();
}
}
或这个:
public class ServiceHelper
{
private readonly DataContext _ctx = new DataContext(Uri);
public void DoSomething()
{
//do something with _ctx and call SaveChanges()
}
public int GetSomething()
{
return _ctx.GetSomething();
}
}
?
另外,我还应该补充一点,这是在ASP.NET MVC应用程序的上下文中进行的,因此将在每个页面请求上重建此处的ServiceHelper类.
编辑
好的,按照Msft的说法,这两种方法在技术上都是有效的,因为它们都是短暂的类,但是我仍然想知道这两种方法是否同样“安全”且等效.也就是说,如果我添加/更新了一些实体并调用SaveChanges,则可能是一个单独的应用程序对相同实体进行了更新,然后我使用相同的上下文实例再次检索了这些实体,这一切都将与我创建一个我第二次手术之前的新环境?
结论
我刚刚发现了this,我认为这有助于解释差异:
By default, the client only materializes an entry in the response feed
into an object for entities that are not already being tracked by the
DataServiceContext. This means that changes to objects already in the
cache are not overwritten. This behavior is controlled by specifying a
MergeOption value for queries and load operations. This option is
specified by setting the MergeOption property on the
DataServiceContext. The default merge option value is AppendOnly. This
only materializes objects for entities that are not already being
tracked, which means that existing objects are not overwritten.
Another way to prevent changes to objects on the client from being
overwritten by updates from the data service is to specify
PreserveChanges. When you specify OverwriteChanges, values of objects
on the client are replaced by the latest values from the entries in
the response feed, even if changes have already been made to these
objects.
因此,如果我先更新一些实体,然后再由一个单独的应用程序进行进一步的更改,然后再使用相同的DataServiceContext实例再次检索这些实体,则这取决于将MergeOption设置为什么状态,是否可以使它们处于实体状态是在数据库中还是刚好在我上次在本地拥有它们的状态.
解决方法:
号码says it
In general, a DataContext instance is designed to last for one “unit
of work” however your application defines that term. A DataContext is
lightweight and is not expensive to create. A typical LINQ to SQL
application creates DataContext instances at method scope or as a
member of short-lived classes that represent a logical set of related
database operations.
当然,您提供使用LINQ to SQL.但是即使在其他技术/库中,上下文通常也是非常轻量的对象.在大多数情况下,物理连接不会断开(但逻辑上是断开).我想您可能关心的是连接池,因此,只要您使用一个(应该使用),然后按照msdn的建议进行即可.所以
public void DoSomething()
{
using(DataContext ctx = new DataContext(Uri))
{
//do something with the context and call SaveChanges()
}
}
标签:wcf,c,dataservice 来源: https://codeday.me/bug/20191121/2054401.html