实体框架。 Where子句,带有来自查询的参数作为变量

时间:2016-02-25 07:56:44

标签: entity-framework linq linq-to-entities expression

任务:在一个查询中使用不同的where子句

以下是示例(这不是真正的查询,只是为了说明问题)

var events = ctx.Events; // ctx - EntityFramework context
var res = events
    .GroupBy(ee => ee.State)
    .Select(gg => new
    {
        State = gg.Key,
        FirstTwo = events
            // how to get this clause from variable
            .Where(ee => ee.State == gg.Key) 
            .Take(2)
    })
    .ToList();

下一个代码不起作用,问题是表达式使用来自查询gg.Key的参数

var events = ctx.Events;
var res = events
    .GroupBy(ee => ee.State)
    .Select(gg => new
    {
        State = gg.Key,
        FirstTwo = events
            // 1
            // how to get this clause from variable
            //.Where(ee => ee.State == gg.Key)

            // 2
            // try to take out where expression from query
            .Where(_buildExpression(gg.Key))
            .Take(2)
    })
    .ToList();

// method
static Expression<Func<Event, bool>> _buildExpression(string state)
{
    return ee => ee.State == state;
}

// exeption
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll
Additional information: variable 'gg' of type 'System.Linq.IGrouping`2[System.String,Entities.Event]' referenced from scope '', but it is not defined

从变量获取表达式的示例,但不依赖于gg.Key(错误)

Expression<Func<Event, bool>> whereClause = (ee) => (ee.State == "test");

var events = ctx.Events;
var res = events
    .GroupBy(ee => ee.State)
    .Select(gg => new
    {
        State = gg.Key,
        FirstTwo = events

            // 1
            // how to get this clause from variable
            //.Where(ee => ee.State == gg.Key)

            // 2
            // try to take out where expression from query
            //.Where(_buildExpression(gg.Key))

            // 3
            // whereClause from variable, but does not depend on gg.Key
            .Where(whereClause)
            .Take(2)
    })
    .ToList();

如何从变量中获取сlause取决于gg.Key?

P.S。查询只是问题的一个例子。下面的代码无法解决真正的查询问题:

var events = ctx.Events;
var res = events
    .GroupBy(ee => ee.State)
    .Select(gg => new
    {
        State = gg.Key,
        FirstTwo = gg.Take(2)
    })
    .ToList();

1 个答案:

答案 0 :(得分:0)

OP解决方案。

感谢Ivan Stoev的评论。

nrow<-nrow(df) #df is your dataset
training_set<-df[seq(1,nrow,by=2),] #select only odds rows
test_set<-df[seq(10,nrow,by=10),] #select only rows by 10

这可以通过LinqKit

实现