[英]Linq static method in SELECT statement
I'm working with EF and have some queries. 我正在与EF合作并有一些疑问。 Here is my code
这是我的代码
IEnumerable<Customer> customers = from c in context.Customers
select new Customer
{
ID = c.ID,
Name = c.Name,
LastName = c.LastName,
DepID = c.DepID,
Editable = SomeStruct.Check(c.DepID)
}
public struct SomeStruct
{
public static bool Check(int depID)
{
//Here I have some logic
}
}
It works fine. 它工作正常。 However, if I declare
SomeStruct
as class
it will fail. 但是,如果我将
SomeStruct
声明为class
,它将失败。
My questions are: 我的问题是:
In your code method SomeStruct.Check(c.DepID)
should be transformed to SQL query. 在您的代码方法中,
SomeStruct.Check(c.DepID)
应该转换为SQL查询。 This describes behaviour with class/structs and so on. 这描述了类/结构的行为等。 It is due to different work of Entity Framework with such methods in class and structure.
这是由于Entity Framework在类和结构中使用这些方法的不同工作。 But you can do this check on client:
但是您可以在客户端进行此检查:
IEnumerable<Customer> customers = from c in context.Customers
select new
{
ID = c.ID,
Name = c.Name,
LastName = c.LastName,
DepID = c.DepID
}
.AsEnumerable()
.Select(d=>new Customer
{
ID = c.ID,
Name = c.Name,
LastName = c.LastName,
DepID = c.DepID,
Editable = SomeStruct.Check(c.DepID)
});
Or you can set Editable property as readonly property: 或者,您可以将Editable属性设置为readonly属性:
public class Customer{
public int ID{get;set;}
public string Name{get;set;}
public string LastName {get;set;}
public Guid DepID{get;set;}
public bool Editable{get{return SomeStruct.Check(DepID);}}
}
It is easily reproducible that your code can not work with linq to entities. 很容易重现,您的代码无法使用linq实体。 Anything that can not be translated into sql will throw a runtime exception.
任何无法转换为sql的内容都会引发运行时异常。 In you case:
在你的情况下:
NotSupportedException: LINQ to Entities does not recognize the method 'Boolean Check(Int32)' method, and this method cannot be translated into a store expression.
NotSupportedException:LINQ to Entities无法识别方法'Boolean Check(Int32)'方法,并且此方法无法转换为商店表达式。
If you got it running at some point, that can not have been related to struct
or class
differences, see What's the difference between a static struct method and a static class method? 如果你在某个时刻运行它,那与
struct
或class
差异无关,请参阅静态结构方法和静态类方法之间的区别是什么?
You probably changed something else at the same time, like adding ToList()
before the select
. 您可能同时更改了其他内容,例如在
select
之前添加ToList()
。
Supposing it's a runtime issue, in many cases you are describing, this is a reference issue. 假设它是一个运行时问题,在您描述的许多情况下,这是一个参考问题。 EF's linq provider supports calling a static method declared in a class (static or not).
EF的linq提供程序支持调用类中声明的静态方法(静态或非静态)。
I recommend that you to change your struct to a class AND make it static to help you investigate the issue. 我建议您将结构更改为类并将其设置为静态以帮助您调查问题。
No, nothing will be executed before you calling a first iteration or customers. 不,在您调用第一次迭代或客户之前不会执行任何操作。
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.