0

If I have a set of tables, TableA, TableB, TableC and TableD with TableA having one to many relationships with TableB, TableC and TableD.

Sometimes I want to return the entire set of TableA, TableB, TableC and TableD. Sometimes I want to return just TableA.

At the moment I have the following:

TableA tableA;

if (includeRelationships)
{
    tableA = (from a in context.TableAs
                   .Include("TableBs")
                   .Include("TableCs")
                   .Include("TableDs")
              where a.Id = myId
              select a).SingleOrDefault();
}
else
{
    tableA = (from a in context.TableAs
              where a.Id = myId
              select a).SingleOrDefault();
}

// do stuff with tableA

Is this the only way to do this?

EDIT - Clarification following feanz's answer:

This will be exposed as a WCF service so it needs to be a single DB call, either all tables or single TableA, so Lazy / Deferred Loading is not an option.

Shevek
  • 3,869
  • 5
  • 43
  • 63

3 Answers3

0

Do something like this

var query = context.TableA;
if (includeRelationships) 
{
   query = query.Include("Tableb").Include("TableC").Include("TableD");
}
var tablea = query.SingleOrDefault();

In this case you are using the fact that the extension method "Include" takes and returns an IQueryable. You might want to use the:

query.Include(x => x.TableB)...

overload of the method that takes an expression as a parameter. That way the compiler will do the checking for you. You may not have access to it if you are using an older version of EF.

sm14
  • 119
  • 2
0

Becasue EF Support Lazy loading by Default the second example:

 tableA = (from a in context.TableAs
          where a.Id = myId
          select a).SingleOrDefault();

Will still have TableBs,TableCs and TableDs as parameters that you can access. The first time these parameters are accessed EF should fire of the query to get the appropriate information. This can be a perf issue and leed to N+1 issues, however in some situations it desirable as like you mentioned you may not want to always get the data.

EF Lazy Loading Info

Richard Forrest
  • 3,567
  • 2
  • 23
  • 32
  • ah, probably should have added that this is part of a WCF service so Lazy Loading isn't really an option – Shevek Jun 08 '11 at 17:27
  • according to the article you linked to, you have to specifically `.Load()` before the references are access, it's not done automatically. either way, it still means multiple trips to the DB instead of one so it's not suitable for this application. – Shevek Jun 08 '11 at 21:20
-1

use

context.ContextOptions.LazyLoadingEnabled = true;
lante
  • 7,192
  • 4
  • 37
  • 57