1

This works:

using (var dbContext = new SmartDataContext())
{
    dbContext.Configuration.ProxyCreationEnabled = false;

    var query = dbContext.EntityMasters.OfType<Person>();
    if (includeAddress)
        query.Include(p => p.Addresses);
    if (includeFiles)
        query.Include(p => p.FileMasters);

    output.Entity = query.Include(s=>s.Addresses).FirstOrDefault<Person>(e => e.EntityId == id);
}

while this doesn't:

using (var dbContext = new SmartDataContext())
{
    dbContext.Configuration.ProxyCreationEnabled = false;

    var query = dbContext.EntityMasters.OfType<Person>();
    if (includeAddress)
        query.Include(p => p.Addresses);
    if (includeFiles)
        query.Include(p => p.FileMasters);

    output.Entity = query.FirstOrDefault<Person>(e => e.EntityId == id);
}

I am trying to include Addresses, Files based on boolean flags coming from function. However it seems, EF not including them when using IF condition.

This is related to my previous question which actually worked using Include.

1
  • Rule of thumb: If you have to say "Edit" to put in an edit, then you don't really need the edit. Commented Jul 9, 2015 at 21:13

2 Answers 2

2

You need to assign the result of Include back to query

query = query.Include(p => p.Addresses);
Sign up to request clarification or add additional context in comments.

Comments

0

Entity framework's 'Include' function only works when it is connected to the entire linq query that was looking up the entity. This is because the linq query is actually a form of Expression that can be inspected as a whole before it is executed.

In the second example there the Person object is already detached from the database so EF has no information on which table Person came from and how it should join Person with the address table to get the results you want.

If you turn on dynamic proxy generation EF is able to keep track of the relation between the entity and the database. However, I'm not sure if this will make the include statement work.

1 Comment

I am not convinced with your statement. When you say Person object is already detached from database, what do you mean? Its a IQueryable object and query variable is holding the query that's being modified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.