LINQ-SQL - using readonly static fields in CompiledQuery.Compile?

I ran into a weird problem using CompiledQuery.Compile . When I try to use the readonly static field in the request, I get the following error message:

 Class member X is unmapped 

If I transfer a field rejection from a partial class to another class not related to LINQ-SQL, then I get the following:

 Object reference not set to an instance of an object 

If I pass fields through an argument, I see no errors and the query works fine and generates the expected SQL.

An example is as follows:

 partial class Order { public static readonly string Complete = "Complete"; public static readonly string Pending = "Pending"; public static readonly Func<DataContext, Order, bool> IsComplete = CompiledQuery.Compile((DataContext context, Order o) => Complete == o.Status); } 

Using:

 var test = from o in db.Orders select new { IsComplete = Order.IsComplete(db, o) }; 

This generates errors. If I add string[] as another argument to CompiledQuery , then I see no errors. Also, if I change the lines as const instead of static readonly , this also works, but I suppose this is due to the values ​​assigned at compile time.

Is there a way to get static readonly fields?

+4
source share
2 answers

The problem arises because Linq-To-Sql tries to translate your expression into backend SQL, because there is an unmapped class element in the logic that it cannot handle its conversion.

I would suggest you create a wrapper property to do the job for you

 partial class Order { public static readonly string Complete = "Complete"; public static readonly string Pending = "Pending"; private static readonly Func<DataContext, Order, bool> _isComplete; public static Func<DataContext, Order, bool> IsComplete { get { if (_isComplete == null) { var complete=Complete; _isComplete CompiledQuery.Compile((DataContext context, Order o) => complete == o.Status); } return _isComplete; } } } 

}

+2
source

No problem if you do not mix regular queries and compiled queries. The following works and will give you better overall performance, due to the fact that you cannot reuse the simple IsCompleted compiled wherever you like.

 public static readonly Func<YourDataContext, IEnumerable<Order>> GetCompletedOrders = CompiledQuery.Compile((YourDataContext context) => context.Orders.Where(o => Complete == o.Status)); 
0
source

Source: https://habr.com/ru/post/1379104/


All Articles