【发布时间】:2009-11-05 13:39:12
【问题描述】:
我了解在从 LINQ-to-SQL 类获取数据时使用using 块是一种很好的做法,如下所示。
但是,当我这样做时,我只能访问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;
}
}
}
}
答案:
感谢 Adam,根据您的建议,我的代码可以像这样工作:
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;
}
【问题讨论】:
标签: c# linq-to-sql datacontext