SWeko
SWeko

Reputation: 30882

Optional join with Entity Framework

I have a situation when I have to load data from several table into a single object, i.e. I have separate tables for BasicProperties and several kinds of "advanced" properties` (I'm not allowed to refactor either the database or the object model).

However, since loading the advanced properties is expensive, and unnecessary in most cases, I want to omit it, unless explicitly specified.

What I currently have is something like:

  from basics in ctx.Basics
    join numerics in ctx.Numerics on basics.ID equals numerics.ItemID
    join alphas in ctx.Alphas on basics.ID equals alphas.Itemid
    join cplx in ctx.Complex on basics.ID equals cplx.Itemid into complex
  select new HodgePodge
             {
               Basics = basics,
               Numerics = numerics,
               Alphas = alpha,
               Complex = complex
             };

so I need some (easy) way to include / exclude the loading of the Numerics, Alphas and Complex database tables.

Basically, I'm a "guest" on this project trying to optimize the loading code, so I'm not allowed to change the code too much, and the worst-case performance must stay at least the same.

Upvotes: 3

Views: 294

Answers (2)

Aducci
Aducci

Reputation: 26644

You can move your join logic into the select statement, and based on your relationship type (1:1, 1:*) you use FirstOrDefault or Where

bool loadNumerics = true;
bool loadAlphas  = true;
bool loadComplex = true;

var query = from basics in ctx.Basics
            select new HodgePodge
            {
               Basics = basics,
               Numerics = ctx.Numerics.FirstOrDefault(x => loadNumerics == true && basics.ID == x.ItemID),
               Alphas = ctx.Alphas.FirstOrDefault(x => loadAlphas == true && basics.ID == x.Itemid),
               Complex = ctx.Complex.Where(x => loadComplex == true && basics.ID == x.Itemid),
            };

Upvotes: 2

Amir Sherafatian
Amir Sherafatian

Reputation: 2083

you can try this:

IQueryable<HodgePodge> Query = ctx.Basics.Select(u => new HodgePodge(){ Basic = u }).AsQueryable();

        if(ConditionNumeric)
            Query = Query.Join(ctx.Numerics,
                q => q.Basic.ID,
                n => n.Itemid,
                (q, n) => new HodgePodge(){ Basic = q.Basic, Numeric = n })
            .AsQueryable();

        if(ConditionAlpha)
            Query = Query.Join(ctx.Alphas,
                q => q.Basic.ID,
                a => a.Itemid,
                (q, a) => new HodgePodge(){ Basic = q.Basic, Alpha = a })
            .AsQueryable();

        if(ConditionComplex)
            Query = Query.Join(ctx.Complex,
                q => q.Basic.ID,
                c => c.Itemid,
                (q, c) => new HodgePodge(){ Basic = q.Basic, Complex = c })
            .AsQueryable();

        return Query.ToList();

Upvotes: 1

Related Questions