为什么实体框架不能在LINQ语句中使用的ToString()? [英] Why would Entity Framework not be able to use ToString() in a LINQ statement?

查看:775
本文介绍了为什么实体框架不能在LINQ语句中使用的ToString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

工作在LINQ到SQL:

This works in LINQ-to-SQL:

var customersTest = from c in db.Customers
                select new
                {
                    Id = c.Id,
                    Addresses = from a in db.Addresses where c.Id.ToString() == 
                        a.ReferenzId select a
                };

foreach (var item in customersTest)
{
    Console.WriteLine(item.Id);
}

但在实体框架类似的例子获取一个错误消息,说基本上是不能它翻译成SQL,这里是德国原来的错误消息:

But a similar example in Entity Framework gets an error message that says basically that it can't "translate it to SQL", here is the original error message in German:

LINQ到实体erkennt模
  梅索德'System.String的ToString()
  nicht,UND diese了Methode卡恩nicht在
  einen Speicherausdruckübersetzt
  werden。

"'LINQ to Entities' erkennt die Methode 'System.String ToString()' nicht, und diese Methode kann nicht in einen Speicherausdruck übersetzt werden."

翻译:

LINQ到实体不承认
  方法'System.String的ToString(),
  这种方法不能被翻译成
  内存前pression。

"'LINQ to Entities' does not recognize Method 'System.String ToString()', this method can not be translated into a memory expression.

任何人都可以揭示我们如何能得到这种说法在实体框架工作或解释它为什么得到这个错误任何光线?

推荐答案

简而言之:LINQ到实体不知道从你的ID类型为字符串转换

Simply put: LINQ to Entities doesn't know about the conversion from your ID type to a string.

什么是 c.ID 的类型?是否有任何理由为什么它是一种类型的ID,但另一个 ReferenzId ?如果可能的话,让他们同一类型,此时你不会有问题了。我不知道是否有LINQ执行转换到实体的其他方式 - 有可能是 - 但调整的类型将是清洁

What is the type of c.ID? Is there any reason why it's one type for ID, but another for ReferenzId? If at all possible, make them the same type, at which point you won't have a problem any more. I don't know if there are other ways of performing conversions in LINQ to Entities - there may be - but aligning the types would be cleaner.

顺便说一句,这真的看起来就像是一个连接:

By the way, this really looks like it's a join:

var query = from c in db.Customers
            join a in db.Addresses on c.Id equals a.ReferenzId into addresses
            select new { Id = c.Id, Addresses = addresses };

编辑:为了回答您的评论 - 的ToString 出现在智能感知因为编译器有什么您的查询将意味着或将如何被翻译没有真正的想法。这是完全合法的C#,并能产生一个有效的前pression树 - 它只是EF不知道如何处理前pression树转换为SQL

To respond to your comment - ToString appears in IntelliSense because the compiler has no real idea what your query is going to mean or how it will be translated. It's perfectly valid C#, and can generate a valid expression tree - it's just that EF doesn't know how to convert that expression tree into SQL.

您可以的尝试的使用 Convert.ToString(c.Id)而不是只调用 c.Id.ToString () ...

You could try using Convert.ToString(c.Id) instead of just calling c.Id.ToString()...

这篇关于为什么实体框架不能在LINQ语句中使用的ToString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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