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:
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); } }
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With