LINQ有条件地添加加入 [英] LINQ Conditionally Add Join

查看:155
本文介绍了LINQ有条件地添加加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LINQ查询,试图从2个表中返回数据,但是我加入的表是有条件的.

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

这就是我想要做的:

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;
}

然后,稍后我将进一步过滤查询.我显然不能以这种方式进行设置,因为我无法在if块之外访问查询",但是它显示了我正在尝试执行的操作.这是我稍后尝试使用查询进行操作的一个示例:

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
         }
}

我要返回的是表foo中的所有数据,然后是联接表中的一个字段,但是根据逻辑,联接表将有所不同. PeopleExtendedInfoA和PeopleExtendedInfoB都具有"Hobby"列,但是我无法从联接表中访问"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.

我该怎么做?

推荐答案

PeopleExtendedInfoAPeopleExtendedInfoB是否从同一基类继承?您可以创建一个IQueryable<BaseClass>,并在添加连接时让linq提供程序为您解决它.例如:

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
            };

这篇关于LINQ有条件地添加加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆