Raw SQL Query without DbSet - Entity Framework Core

后端 未结 17 1197
眼角桃花
眼角桃花 2020-11-22 13:27

With Entity Framework Core removing dbData.Database.SqlQuery I can\'t find a solution to build a raw SQL Query for my full-text search query th

17条回答
  •  孤街浪徒
    2020-11-22 13:38

    Building on the other answers I've written this helper that accomplishes the task, including example usage:

    public static class Helper
    {
        public static List RawSqlQuery(string query, Func map)
        {
            using (var context = new DbContext())
            {
                using (var command = context.Database.GetDbConnection().CreateCommand())
                {
                    command.CommandText = query;
                    command.CommandType = CommandType.Text;
    
                    context.Database.OpenConnection();
    
                    using (var result = command.ExecuteReader())
                    {
                        var entities = new List();
    
                        while (result.Read())
                        {
                            entities.Add(map(result));
                        }
    
                        return entities;
                    }
                }
            }
        }
    

    Usage:

    public class TopUser
    {
        public string Name { get; set; }
    
        public int Count { get; set; }
    }
    
    var result = Helper.RawSqlQuery(
        "SELECT TOP 10 Name, COUNT(*) FROM Users U"
        + " INNER JOIN Signups S ON U.UserId = S.UserId"
        + " GROUP BY U.Name ORDER BY COUNT(*) DESC",
        x => new TopUser { Name = (string)x[0], Count = (int)x[1] });
    
    result.ForEach(x => Console.WriteLine($"{x.Name,-25}{x.Count}"));
    

    I plan to get rid of it as soon as built-in support is added. According to a statement by Arthur Vickers from the EF Core team it is a high priority for post 2.0. The issue is being tracked here.

提交回复
热议问题