我应该使用哪个来正确处理WCF中的Linq-to-SQL上下文?
这是我的示例界面
public interface IMyWebService
{
[OperationContract]
List<MyTable> GetMyStuff();
}
这是我的svc.cs
。在WCF中部署Linq-to-SQL数据上下文的首选方法是什么?
public class MyWebService : IMyWebService
{
public List<MyTable> GetMyStuff()
{
IQueryable<MyTable> myTable;
using (var db = new MyWebServiceDatabaseDataContext())
{
myTable = db.MyTable.Select(a => a);
}
return myTable.ToList();
}
////OR
public List<MyTable> GetMyStuff()
{
var db = new MyWebServiceDatabaseDataContext();
var myTable = from a in db.MyTable
select a;
return myTable.ToList();
}
}
答案 0 :(得分:2)
使用using语句
using(var db = new MyWebServiceDatabaseDataContext())
{
var myTable = from a in db.MyTable
select a;
return myTable.ToList();
}
它将自动处理你的上下文。这个语句在幕后转换如下:
try
{
var db = new MyWebServiceDatabaseDataContext();
var myTable = from a in db.MyTable
select a;
return myTable.ToList();
}
finally
{
db.Dispose();
}