Reputation: 851
I'm working with EF and have some queries. 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.
My questions are:
Upvotes: 6
Views: 6823
Reputation: 11964
In your code method SomeStruct.Check(c.DepID)
should be transformed to SQL query. 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. 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:
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); } }
}
Upvotes: 6
Reputation: 109185
It is easily reproducible that your code can not work with linq to entities. Anything that can not be translated into sql will throw a runtime exception. 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.
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?
You probably changed something else at the same time, like adding ToList()
before the select
.
Upvotes: 1
Reputation: 3111
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).
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
Upvotes: 0