我知道在從LINQ-to-SQL類獲取數據時使用using
塊是一種很好的做法,如下所示。在方法中處理DataContext的最佳LINQ-to-SQL策略是什麼?
然而,我這樣做時,我只能因爲它們似乎在這一點上設置的訪問的orders
(例如Order.OrderId
),但不更深性質(例如Customer.CustomerName
)淺性質。
我可以拿出我的using
塊,它允許我訪問客戶,但是這不會釋放資源。
這裏的最佳做法是什麼?
using System;
using System.Collections.Generic;
using System.Linq;
using TestExtn2343.Models;
namespace TestExtn2343
{
class Program
{
public static void Main(string[] args)
{
var orders = GetOrders(10, 10);
orders.ForEach(x =>
{
Customer customer = x.Customer;
if (customer != null)
{
//SUCCEEDS:
Console.WriteLine("{0}, {1}", x.OrderID);
//FAILS: "
Console.WriteLine("{0}, {1}", x.OrderID, x.Customer.ContactName.ToString());
}
});
Console.ReadLine();
}
public static List<Order> GetOrders(int skip, int take)
{
using (MainDataContext db = new MainDataContext())
{
List<Order> orders = (from order in db.Orders
select order).Skip(skip).Take(take).ToList();
return orders;
}
}
}
}
答:
感謝亞當,用你的建議,我有我的代碼工作是這樣的:
public static void Main(string[] args)
{
using (MainDataContext db = new MainDataContext())
{
GetOrders(db, 10, 10).ForEach(x => Console.WriteLine("{0}, {1}", x.OrderID, x.Customer.ContactName.ToString()));
}
Console.ReadLine();
}
public static List<Order> GetOrders(MainDataContext db, int skip, int take)
{
List<Order> orders = (from order in db.Orders
select order).Skip(skip).Take(take).ToList();
return orders;
}