【问题标题】:LINQ To SQL exception: Local sequence cannot be used in LINQ to SQL implementationLINQ To SQL 异常:不能在 LINQ to SQL 实现中使用本地序列
【发布时间】:2010-10-21 08:36:21
【问题描述】:

大家。 我知道,这个话题已经讨论过了。但是,不幸的是,我在现有答案中没有找到任何解决方案。所以,我有下一个代码:

public List<List<string>> DataTableParser(IQueryable<T> queriable)
    {
        //I missed the unnecessary code

        return queriable.Select(SelectProperties).ToList();

        //I missed the unnecessary code        
    }

    private Expression<Func<T, List<string>>> SelectProperties
    {
        get
        {
            var properties = typeof(T).GetProperties();
            // 
            return value => properties.Select
                                        (
                // empty string is the default property value
            prop => (prop.GetValue(value, null) ?? string.Empty).ToString()
                                        )
                                       .ToList();
        }
    }

因此,在 DataTableParser 方法中,下一条消息出现异常:
“本地序列不能在 LINQ to SQL 的查询运算符实现中使用,但 Contains() 运算符除外”。 我不在我的查询“where”部分中使用。所以我无法想象如何使用“包含”运算符。而且我无法理解异常的原因。 有没有人有任何想法?我将不胜感激。谢谢。

【问题讨论】:

  • properties 变量是什么?
  • 对不起,乔恩,我忘记了。我将它添加到代码中。 var properties = typeof(T).GetProperties();

标签: c# sql linq


【解决方案1】:

尝试使用

return queriable.AsEnumerable().Select(SelectProperties).ToList();

这首先评估可查询对象的 sql 并在内存中创建对象,然后可以通过反射处理这些对象

linq to sql 只知道如何将表达式转换为 sql。可转换为 sql 的表达式数量有限。代表您的列的属性可转换为 sql。

queriable.Select(x=>x.MyColumn);
//is translatable to sql when there is a column that is named MyColumn in your table

queriable.Where(x=>x.MyColumn.Contains("X"))
//is translatable to sql as "...where MyColumn like '%X%' ..."

queriable.Select(x=> new { x.MyColumn, x.AnotherColumn})
//is translatable to sql for selecting multiple columns

queriable.Select(SelectProperties)
//is not translatable to sql because it does not return an expression that selects a single value, and its not an expression that returns a new object.

你打算如何使用这个方法?

【讨论】:

  • 你好,蒂恩。谢谢您的回答。我很感激你的例子。他们帮助我理解问题。但是你的建议“return queriable.AsEnumerable().Select(SelectProperties).ToList();”没有帮助我。无法从用法中推断出类型参数。
  • 你能说明你是如何使用这个功能的吗?你在传递什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多