代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

在方法中处理DataContext的最佳LINQ to SQL策略是什么?

  •  0
  • Edward Tanguay  · 技术社区  · 16 年前

    我知道使用 using

    orders Order.OrderId Customer.CustomerName

    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;
    }
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   Adam Robinson    16 年前

    (也就是说,它会根据需要自动检索这些记录,因此当您第一次访问它们时,它会执行数据库操作)。因为 DataContext

    数据上下文 数据上下文 需要在该方法之外声明并传入(甚至在您的 数据上下文 ).

    blog post 数据上下文

        2
  •  1
  •   Joseph    16 年前

    msdn article on DataLoadOptions .

    var dlo = new DataLoadOptions();
    dlo.LoadWith<Order>(o => o.Customer); 
    context.DataLoadOptions = dlo;