Save Entity Framework Linq Query to database

entity-framework-4 expression-trees linq serialization


I was wondering if we can convert a Linq Query on the Entity Framework and save the query to the database by converting it to an Expression Tree and Serializing. Can someone please help me on this and point me in a right direction whether this can be done or not. Any help is greatly appreciated on this.

Thanks, Ajay.

7/9/2012 11:37:56 PM

Accepted Answer

i released a library for that purpose just yesterday. Serialize.Linq. It serializes linq expressions to 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");

9/22/2012 10:21:09 AM

Popular Answer

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


public class TestSprintOData
    public static void Run()
        // Parse a Func into string
        var query = Filter.Serialize<User>(u => u.IsActive && u.Email.Contains(""));

        // It'll generate the string "IsActive and substringof('', 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 = ""},
            new User{Name="abc", IsActive = false, Email = ""},
            new User{Name="dude", IsActive=true, Email = ""}

        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

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow