我有以下情况:
我需要在EF上下文中执行以下linq查询
from table1 in context.TableOne
join table2 in context.TableTwo on table1.SomeFKId equals table2.Id
join table3 in context.TableThree on table2.SomeFKId equals table3.Id
...
join tableN in context.TableN on tableN_1.SomeFKId equals tableN.Id
where case1 && case2 && case3 ... && caseN
select new TablesDto { VarOne = table1.Var , VarTwo = tableN_2.var }
我的问题是我想在diffirent senarios中使用相同的查询,并且有很多扩展。 我宁愿不写多次(DRY原则)只是扩展它,但不是以效率和速度为代价。
如果我想要将第一个表连接到另一个表,我可以扩展Dto以合并其余的变量但是如果我要遍历行,我需要每行查询来扩展它。由于我在谈论100到5000行,即使迭代也需要一些时间。
扩展包括:其他情况(case1,case2等)和其他连接。
扩展示例:
from table1 in context.TableOne
join table2 in context.TableTwo on table1.SomeFKId equals table2.Id
join table3 in context.TableThree on table2.SomeFKId equals table3.Id
...
join tableN in context.TableN on tableN_1.SomeFKId equals tableN.Id
join extTable in context.TableExt on table2.SomeFKId equals extTable.Id
where case1 && case2 && case3 ... && caseN || extTable.NumOfSmth == 4
select new ExtTablesDto { VarOne = table1.Var , VarTwo = tableN_2.var , ExtVar = extTable.Name }
答案 0 :(得分:2)
试试这个......
void Main()
{
using(var dal = new DataAccessLayer())
{
var items = dal.TablesDtoQuery.Case1().Case2().ToList();
}
}
public class DataAccessLayer : IDisposable
{
private DbContext context;
public void Dispose()
{
context.Dispose();
}
public IQueryable<TablesDto> TablesDtoQuery
{
get
{
return
from table1 in context.TableOne
join table2 in context.TableTwo on table1.SomeFKId equals table2.Id
join table3 in context.TableThree on table2.SomeFKId equals table3.Id
...
join tableN in context.TableN on tableN_1.SomeFKId equals tableN.Id
where case1 && case2 && case3 ... && caseN
select new TablesDto { VarOne = table1.Var , VarTwo = tableN_2.var };
}
}
}
public static class TablesDtoQueryExtension
{
public IQueryable<TablesDto> Case1(this IQueryable<TablesDto> query)
{
return from t in query
where ...
select t;
}
public IQueryable<TablesDto> Case2(this IQueryable<TablesDto> query)
{
return from t in query
where ...
select t;
}
}
答案 1 :(得分:1)
你可以像这样扩展where查询
var query = from user in dbContext.Users where user.id = 10;
if (x == 3)
{
query = query.where(p=>p.name == "test");
}
等等你可以在这里扩展基本查询,你将在UserId = 10和name =&#34之后搜索;测试&#34;
如果您有EF模型,那么您应该尝试在那里创建表之间的依赖关系,然后您不需要在查询中加入它们