Sql statement to execute a query in the operation of the EF Core FromSql, ExecuteSqlCommand, SqlQuery

First, the current EF Core version is V2.1

Compared EF Core v1.0 now adds a lot of functionality.

EF Core addition to the usual CRUD operations model, Sql statements in a number of projects can not be avoided.

In EF Core context, you can return goods DbConnection, execute sql statement. This is the lowest level of operation, or with a lot of code to write.

In addition to the initial EF Core also supports FromSql, ExecuteSqlCommand even a method for easier implementation of Sql statement.

In addition, the current version of EF Core does not support SqlQuery, but we can extend its own. Wait for it to support future upgrades.

1.FromSql, query execution list

public static IQueryable<TEntity> FromSql<TEntity>([NotNullAttribute] this IQueryable<TEntity> source, 
[NotParameterized] RawSqlString sql,
[NotNullAttribute] params object[] parameters) where TEntity : class;

In this manner, only the text lines on the current model object registered.

For context DbSet <T> are not defined ineffective.

Code Example 1:

Copy the code
    // execute sql query FromSql ()
    QLLB_SWXContext _Context = new QLLB_SWXContext();
    string sql = "select * from Article where CategoryID=1;";
    List<Article> list = _Context.Article.FromSql(sql).ToList();
    foreach (var item in list)
    {
        Console.WriteLine(item.Title);
    }
Copy the code

Code Example 2: Query view

Copy the code
--- create a view, query menu does not assign roles
create view view_NoRole
as 
select * from Sys_Navigation
where NavID not in (
select distinct  NavID   from Sys_Role_Nav 
)
Copy the code
Copy the code
// Query View
    string sql2 = "select * from view_NoRole";
    List<SysNavigation> roleList = _Context.SysNavigation.FromSql(sql2).ToList();
    foreach (var item in roleList)
    {
        Console.WriteLine(item.Title);
    }
Copy the code

2.ExecuteSqlCommand, performs operation processing Sql

QLLB_SWXContext _Context = new QLLB_SWXContext();
// perform data manipulation sql, returns the number of rows affected
string sql = "update Sys_Role set SortValue=1 ;";
int count = _Context.Database.ExecuteSqlCommand(sql);
Console.WriteLine(count);

3. The SqlQuery custom, query execution list, the objects in the line of text does not exist.

Code Example 1:

Copy the code
QLLB_SWXContext _Context = new QLLB_SWXContext();
// specified, custom packaging does not support a single value queries
// does not support object query
// custom query SqlQuery
string sql = "select sum(ViewCount)*1.11 as allCount from Article;";
TempData result = _Context.Database.SqlQuery<TempData>(sql).FirstOrDefault();
Console.WriteLine(result.AllCount);
Copy the code

Object Definition

Copy the code
public class TempData
{
    public int CategoryID { get; set; }
    public string Title { get; set; }
    public int ArtCount { get; set; }
    /// <summary>
    /// summation results
    /// </summary>
    public decimal AllCount { get; set; }
}
Copy the code

Code Example 2:

View query execution:

Copy the code
- the number of articles defining the view, article categories and the corresponding classification
create view view_CateCount
as
select C.CategoryID,C.Title,  (
select count(*) from Article where CategoryID=C.CategoryID
) as ArtCount  from ArticleCategory C;
Copy the code

C # code:

Copy the code
// query combination
string sql2 = "select * from view_CateCount;";
List<TempData> tempList = _Context.Database.SqlQuery<TempData>(sql2).ToList();
foreach (var item in tempList)
{
    Console.WriteLine(item.Title);
}
Copy the code

SqlQuery extended definition:

Copy the code
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;

namespace QL.Card.Entity
{
    public static class DbContextExtensions
    {
        private static void CombineParams(ref DbCommand command, params object[] parameters)
        {
            if (parameters != null)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    if (!parameter.ParameterName.Contains("@"))
                        parameter.ParameterName = $"@{parameter.ParameterName}";
                    command.Parameters.Add(parameter);
                }
            }
        }

        private static DbCommand CreateCommand(DatabaseFacade facade, string sql, out DbConnection dbConn, params object[] parameters)
        {
            DbConnection conn = facade.GetDbConnection();
            dbConn = conn;
            conn.Open();
            DbCommand cmd = conn.CreateCommand();
            if (facade.IsSqlServer())
            {
                cmd.CommandText = sql;
                CombineParams(ref cmd, parameters);
            }
            return cmd;
        }

        public static DataTable SqlQuery(this DatabaseFacade facade, string sql, params object[] parameters)
        {
            DbCommand cmd = CreateCommand(facade, sql, out DbConnection conn, parameters);
            DbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            reader.Close();
            conn.Close();
            return dt;
        }

        public static IEnumerable<T> SqlQuery<T>(this DatabaseFacade facade, string sql, params object[] parameters) where T : class, new()
        {
            DataTable dt = SqlQuery(facade, sql, parameters);
            return dt.ToEnumerable<T>();
        }

        public static IEnumerable<T> ToEnumerable<T>(this DataTable dt) where T : class, new()
        {
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            T[] ts = new T[dt.Rows.Count];
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                T t = new T();
                foreach (PropertyInfo p in propertyInfos)
                {
                    if (dt.Columns.IndexOf(p.Name) != -1 && row[p.Name] != DBNull.Value)
                        p.SetValue(t, row[p.Name], null);
                }
                ts[i] = t;
                i++;
            }
            return ts;
        }
    }
}
Copy the code

 

 

Guess you like

Origin www.cnblogs.com/zmsoftbj/p/11840947.html