Save Entity Framework Linq Query to database

后端 未结 4 623
逝去的感伤
逝去的感伤 2020-12-17 05:28

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

相关标签:
4条回答
  • 2020-12-17 05:33

    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.

    0 讨论(0)
  • 2020-12-17 05:34

    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

    0 讨论(0)
  • 2020-12-17 05:35

    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.

    0 讨论(0)
  • 2020-12-17 05:44

    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());
    
    0 讨论(0)
提交回复
热议问题