Save Entity Framework Linq Query to database

ぐ巨炮叔叔 提交于 2019-12-08 22:22:18

问题


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.


回答1:


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



回答2:


You could turn the query into a string and then save the string.

This is from an answer by Nick Berardi:

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 could be stored and re-used.




回答3:


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




回答4:


You may want to consider using Entity SQL rather than LINQ in this case. Entity SQL is a string query that works against your EF conceptual model rather than directly against the database.



来源:https://stackoverflow.com/questions/11404757/save-entity-framework-linq-query-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!