Entity framework Core Raw SQLQueries with custom model

后端 未结 4 1420
难免孤独
难免孤独 2021-02-14 20:39

Using Entity Framework 6, I was able to use execute a Raw SQL Query and use a custom model which was not defined in the DBContext in order to store the output of the query. A si

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 21:16

    The question was about .NET Core 2. Now I have a solution and I am going to write it here so that someone else could use it in case he/she needs it.

    First of all we add the following method in dbContext class

    public List ExecSQL(string query)
    {
        using (var command = Database.GetDbConnection().CreateCommand())
        {
            command.CommandText = query;
            command.CommandType = CommandType.Text;
            Database.OpenConnection();
    
            List list = new List();
            using (var result = command.ExecuteReader())
            {
                T obj = default(T);
                while (result.Read())
                {
                    obj = Activator.CreateInstance();
                    foreach (PropertyInfo prop in obj.GetType().GetProperties())
                    {
                        if (!object.Equals(result[prop.Name], DBNull.Value))
                        {
                            prop.SetValue(obj, result[prop.Name], null);
                        }
                    }
                    list.Add(obj);
                }
            }
            Database.CloseConnection();
            return list;
        }
    }
    

    Now we can have the following code.

    List Customers = _context.ExecSQL("SELECT ......");
    

提交回复
热议问题