开发者

Linq query makes all calls to bring foreign key's table data

开发者 https://www.devze.com 2023-02-16 03:16 出处:网络
from d in Customers select d; This query makes a call for every customerId to get the orders where customerId = that customerId.
from d in Customers
select d;

This query makes a call for every customerId to get the orders where customerId = that customerId.

This makes the call slow and long, I don't want orders data. How to disable that?

Addtional details:

I'm doing conditional

if (flag)
{
   return (from d in Customers
           select d).ToList();
}    
else
{
   return (from d in Customers
           where d.Orders.Count > 10
           select d).ToList();
}

Even in the if query it makes calls to all the Orders of ea开发者_开发百科ch Customer which I want to prevent in both the cases.


As Craig Stuntz hinted, the question here is where Customers comes from and what type it is. If it's an in-memory object, the filtering is all going to happen in memory; if it's an object query, it'll happen on your database server, which is what you want. We can't see enough of your code to know much about Customers, but I'll suggest a right and wrong example:

Right (more or less):

using (var context = new MyContextType())
{
    var Customers = context.Customers;

    var query = from d in Customers
                select d;

    if (!flag)
    {
       query = from d in query
               where d.Orders.Count > 10
               select d;
    }

    return query.ToList();
}

Wrong:

using (var context = new MyContextType())
{
    var Customers = context.Customers.ToList(); // ToList triggers the query

    var query = from d in Customers
                select d;

    if (!flag)
    {
       query = from d in query
               where d.Orders.Count > 10
               select d;
    }

    return query.ToList();
}

See the difference? It's the context.Customers.ToList(). That runs the full query and loads everything into memory before you have a chance to filter it. Make sure you have the query fully built, including where logic, before you run ToList() on it.

@Craig - Hope you don't mind me picking up your idea and running with it. I'd have voted for your answer if you had one up.


The query you posted doesn't do that. Accessing the Orders property of a customer instance could do that. Don't access the Orders property and you'll be fine.

If your code isn't accessing the Orders property, perhaps some serialization code is... to prevent that code from being able to retrieve data - dispose the data context. To prevent that code from having an Orders property to access, remove the association in the dbml.


I went to the dataModel, and deleted the property Orders from Customers table. and now it works fine, there's just one call. But I can't do e.Orders.Count anymore but I would rather use join instead of doing that to solve this problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消