2014-01-06 53 views
0

我應該使用哪種方法在WCF中正確配置Linq-to-SQL上下文?在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(); 
     } 
    } 
+1

我肯定會推薦使用'(... 。){.....}' - 這個**確保**在使用塊結束時正確處置 –

回答

2

使用using聲明

using(var db = new MyWebServiceDatabaseDataContext()) 
{ 
     var myTable = from a in db.MyTable 
      select a; 
     return myTable.ToList(); 
} 

它會自動處置您的context.This語句轉換這樣的幕後:

 try 
     { 
      var db = new MyWebServiceDatabaseDataContext(); 
      var myTable = from a in db.MyTable 
          select a; 
      return myTable.ToList(); 
     } 
     finally 
     { 
      db.Dispose(); 
     }