linq to sql loadwith vs associatewith

后端 未结 2 1008
闹比i
闹比i 2021-02-07 00:10

what is the difference between loadwith and associatewith. From the articles i read it seems that loadwith is used to load addition data (eg all orders for the customers). While

2条回答
  •  被撕碎了的回忆
    2021-02-07 00:53

    Yes your understanding is correct; AssociateWith filters data before queries whereas LoadWith returns associated objects in the query. The reason for doing LoadWith is so you can return associated objects in 1 single query. Otherwise extra db calls will be made at the time when you iterate over your associated objects.

    Try different examples yourself and take a look at the SQL generated through Profiler or some other logger. Remember that these options need to be set on your DataContext before you do any queries.

    Have a look at the examples in the below links (MSDN). I've just copied the examples they use there.

    LoadWith

    DataLoadOptions dlo = new DataLoadOptions();
    dlo.LoadWith(c => c.Orders);
    db.LoadOptions = dlo;
    
    var londonCustomers = from cust in db.Customers
                          where cust.City == "London"
                          select cust;
    

    AssociateWith

    DataLoadOptions dlo = new DataLoadOptions();
    dlo.AssociateWith(
        c => c.Orders.Where(p => p.ShippedDate != DateTime.Today));
    db.LoadOptions = dlo;
    
    var custOrderQuery = from cust in db.Customers
                         where cust.City == "London"
                         select cust;
    

提交回复
热议问题