Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq static method in SELECT statement

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:

  1. Why does it happens ?
  2. Does using of static function forces the query to execute ?
like image 619
ramil89 Avatar asked Dec 21 '12 07:12

ramil89


2 Answers

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); } }
}
like image 131
Kirill Bestemyanov Avatar answered Oct 14 '22 02:10

Kirill Bestemyanov


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.

like image 21
Gert Arnold Avatar answered Oct 14 '22 02:10

Gert Arnold