Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Conditionally Add Join

I have a LINQ query where I'm trying to return data from 2 tables, but the tables that I join are conditional.

This is what I'd like to do:

if (teamType == "A"){
    var query = from foo in context.People
                join foo2 in context.PeopleExtendedInfoA
                select foo;
}
else {
    var query = from foo in context.People
                join foo2 in context.PeopleExtendedInfoB
                select foo;
}

Then later on I'm filtering the query down even further. I obviously can't set it up this way because I won't be able to access "query" outside the if block, but it shows what I'm trying to do. This is an example of what I'm trying to do later on with the query:

if (state != null)
{
     query = query.Where(p => p.State == state);
}

if (query != null) {
   var queryFinal = from foo in query
         select new PeopleGrid()
         {
              Name = foo.Name,
              Address = foo.Address,
              Hobby = foo2.Hobby
         }
}

What I'm trying to return is all the data from table foo and then one field from the joined table, but depending on the logic, the joined table will differ. Both PeopleExtendedInfoA and PeopleExtendedInfoB both have the columb 'Hobby', but I have no way to access 'Hobby' from the joined table and that's the only field I need from the joined table.

How would I go about doing this?

like image 624
user3653673 Avatar asked Apr 29 '26 08:04

user3653673


1 Answers

Does PeopleExtendedInfoA and PeopleExtendedInfoB inherits from the same base class? You could create a IQueryable<BaseClass> and let the linq provider solve it for you when you add the join. For sample:

IQueryable<BasePeople> basePeople;
if (teamType == "A")
   basePeople = context.PeopleExtendedInfoA;
else
   basePeople = context.PeopleExtendedInfoB;

var query = from foo in context.People
            join foo2 in basePeople on foo.Id equals foo2.PeopleId
            select new PeopleGrid()
            {
              Name = foo.Name,
              Address = foo.Address,
              Hobby = foo2.Hobby
            };
like image 190
Felipe Oriani Avatar answered May 03 '26 16:05

Felipe Oriani