LINQ To SQL异常:本地序列不能在LINQ to SQL实现中使用 [英] LINQ To SQL exception: Local sequence cannot be used in LINQ to SQL implementation

查看:29
本文介绍了LINQ To SQL异常:本地序列不能在LINQ to SQL实现中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

everybody. I know, that this topic has been discussed yet. But, unfortunately, I didn't find any solution in existing answers.So, I have the next code:

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方法中,下一条消息具有异常:
除了在Contains()运算符外,不能在查询运算符的LINQ to SQL实现中使用本地序列".我不在查询中使用"where"部分.因此,我无法想象如何使用包含"运算符.而且我不明白例外的原因.有人有什么想法吗?我将不胜感激.谢谢.

So, in the method DataTableParser I have the exception with the next message:
"Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator". I don't use in my query "where" part. So I can't imagine how to use "Contains" operator. And I can't understand the reason of the exception. Does anyone have any ideas? I will appreciate any help. Thanks.

推荐答案

尝试使用

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

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

this evaluates the sql of the queriable first and creates in memory objects that will then be processable by reflection

linq to sql仅知道如何将表达式转换为sql.可翻译为 sql 的表达式数量有限.表示列的属性可以转换为sql.

linq to sql only knows how to translate an expression into sql. there is a limited number of expressions that are translatable to sql. the properties that represent your columns are translatable to 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.

您打算如何使用此方法?

How do you intend to use this method?

这篇关于LINQ To SQL异常:本地序列不能在LINQ to SQL实现中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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