2

我有以下情况:

我需要在 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 }

我的问题是我想在具有很多扩展的不同场景中使用相同的查询。我宁愿不写很多次(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 }
4

2 回答 2

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;
    } 
}
于 2013-09-25T07:26:43.447 回答
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 = "test" 之后搜索

如果你有一个 EF 模型,那么你应该尝试在那里创建表之间的依赖关系,那么你不需要在你的查询中加入它们

于 2013-09-25T06:53:45.710 回答