Save Entity Framework Linq Query to database

entity-framework-4 expression-trees linq serialization

Question

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.

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");

Console.WriteLine(query.ToJson());
Console.WriteLine(query.ToXml());

Popular Answer

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

Sample:

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



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why