Save Entity Framework Linq Query Object for Database

I was wondering if we can convert Linq Query to Entity Framework and save the database query by translating it into the expression tree and serialization. Can someone please help me on this and call me in the right direction whether this can be done or not. Any help is much appreciated about this.

Thanks, Ajay.

+4
serialization linq expression-trees entity-framework-4
source share
4 answers

I released the library for this purpose only yesterday. Serialize.Linq . It serializes linq expressions for xml, json or binary.

using System.Linq.Expressions using Serialize.Linq.Extensions; Expression<Func<Person, bool>> query = p => p.LastName == "Miller" && p.FirstName.StartsWith("M"); Console.WriteLine(query.ToJson()); Console.WriteLine(query.ToXml()); 
+3
source share

You can include the query in a string and then save the string.

This is Nick Berardi's answer:

 var result = from x in appEntities where x.id = 32 select x; var sql = ((System.Data.Objects.ObjectQuery)result).ToTraceString(); 

The sql generated by the query can be saved and reused.

+1
source share

Use Sprint.Filter.OData . It converts Func<T,bool> to a string and back to code.

Example:

 public class TestSprintOData { public static void Run() { // Parse a Func into string var query = Filter.Serialize<User>(u => u.IsActive && u.Email.Contains("@gmail.com")); // It'll generate the string "IsActive and substringof('@gmail.com', Email)" // Convert back to Expression, perhaps on server var query2 = Filter.Deserialize<User>(query); // Compiles to Func, so you can use as delegate to Where var f = query2.Compile(); var list = new List<User> { new User{Name="Johnny", IsActive = true, Email = "johnny@gmail.com"}, new User{Name="abc", IsActive = false, Email = ""}, new User{Name="dude", IsActive=true, Email = "dude@gmail.com"} }; var result = list.Where(f); } } class User { public string Name; public string Phone; public string Login; public string Email; public bool IsActive; } 

You can also use it as a Nuget Package.

+1
source share

In this case, you may want to use Entity SQL rather than LINQ. Entity SQL is a string query that works against your EF conceptual model, and not directly against the database.

0
source share

All Articles