这在 LINQ-to-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 to Entities' erkennt die方法'System.String ToString()'nicht, und diese Methode kann nicht ineinen Speicherausdruck übersetzt韦登."
"'LINQ to Entities' erkennt die Methode 'System.String ToString()' nicht, und diese Methode kann nicht in einen Speicherausdruck übersetzt werden."
翻译:
"'LINQ to Entities' 无法识别方法 'System.String ToString()',这个方法不能翻译成一个记忆表达.
"'LINQ to Entities' does not recognize Method 'System.String ToString()', this method can not be translated into a memory expression.
谁能解释一下我们如何让这种语句在实体框架中工作或解释为什么会出现这个错误?
简单地说:LINQ to Entities 不知道从您的 ID 类型到字符串的转换.
Simply put: LINQ to Entities doesn't know about the conversion from your ID type to a string.
c.ID
的类型是什么?有什么理由为什么它是 ID 的一种类型,而 ReferenzId
是另一种类型?如果可能,请将它们设为相同类型,此时您将不再有问题.我不知道是否还有其他方法可以在 LINQ to Entities 中执行转换 - 可能有 - 但对齐类型会更清晰.
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
出现在 IntelliSense 中,因为编译器不知道您的查询将意味着什么或将如何翻译.它是完全有效的 C#,并且可以生成有效的表达式树 - 只是 EF 不知道如何将该表达式树转换为 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!