解决方法
>延迟加载:对于给定的实体,它的关联集合在首次加载时可能为空,但是当首次迭代这些集合时,LINQ to sql会在加载后触发查询以加载这些集合,然后该集合可用于未来使用而不需要其他查询:
var query = from o in db.GetTable<Order>() //db is the datacontext select o; foreach(Order o in query) { foreach(OrderDetail d in o.OrderDetails)//Deferred loading { //Do something on these collections } }
OrderDetails仅在迭代时加载,因此如果从不迭代OrderDetatils,则永远不会执行相应的查询.
> Eager Loading:立即加载所有引用实体的关联集合,例如LINQ to sql将自动为所有已检索的订单带来所有OrderDetails
DataLoadOptions op = new DataLoadOptions(); op.LoadWith<Order>(o => o.OrderDetails); db.LoadOptions = op; var query = from o in db.GetTable<Order>() select o; foreach(Order o in query) { //Order details are eager loaded; additional queries are not needed foreach(OrderDetail d in o.OrderDetails) { //do something } }