雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

EF Core 6(EF6)没有SqlQuery方法

2024-06-13 43

对于.Net Framework的 EF

可以直接使用 Entity DbContext 实例化出来的对象,执行SqlQuery执行自定义的SQL语句返回结果集:

_DBContext.Database.SqlQuery<object>(“sql”); 

ExecuteSqlCommand方法可以执行SQL语句,返回影响的数据数量,适合insert update delete 操作。

_DBContext.Database.ExecuteSqlCommand(“sql”);

对于 .Net Core 的 EF Core

如果使用的是EntityFramework 8(EF8)版本,可以使用SqlQuery方法。只要安装EntityFramework Core8,默认包含程序集Microsoft.EntityFrameworkCore.Relational,并且在里面实现了SqlQuery静态扩展方法:

    //
    // 摘要:
    //     Creates a LINQ query based on a raw SQL query, which returns a result set of
    //     a scalar type natively supported by the database provider.
    //
    // 参数:
    //   databaseFacade:
    //     The Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade for the context.
    //
    //
    //   sql:
    //     The interpolated string representing a SQL query with parameters.
    //
    // 返回结果:
    //     An System.Linq.IQueryable`1 representing the interpolated string SQL query.
    //
    // 言论:
    //     To use this method with a return type that isn't natively supported by the database
    //     provider, use the Microsoft.EntityFrameworkCore.ModelConfigurationBuilder.DefaultTypeMapping``1(System.Action{Microsoft.EntityFrameworkCore.Metadata.Builders.TypeMappingConfigurationBuilder{``0}})
    //     method.
    //
    //     The returned System.Linq.IQueryable`1 can be composed over using LINQ to build
    //     more complex queries.
    //
    //     Note that this method does not start a transaction. To use this method with a
    //     transaction, first call Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.BeginTransaction(Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade,System.Data.IsolationLevel)
    //     or UseTransaction.
    //
    //     As with any API that accepts SQL it is important to parameterize any user input
    //     to protect against a SQL injection attack. You can include parameter place holders
    //     in the SQL query string and then supply parameter values as additional arguments.
    //     Any parameter values you supply will automatically be converted to a DbParameter.
    //
    //
    //     See Executing raw SQL commands with EF Core for more information and examples.
    public static IQueryable<TResult> SqlQuery<TResult>(this DatabaseFacade databaseFacade, [NotParameterized] FormattableString sql)
    {
        return databaseFacade.SqlQueryRaw<TResult>(sql.Format, sql.GetArguments());
    }

SqlQuery方法使用示例:

var parameter = new SqlParameter { ParameterName = "categoryid", SqlDbType = SqlDbType.Int, Value = 1 };
var sql = FormattableStringFactory.Create("select * from articles where categoryid=@categoryid", parameter);
var articles = _context.Database.SqlQuery<Article>(sql).ToList();

但是如果使用.NET6对应的EntityFramework 6(EF6)版本,并没有SqlQuery方法。即使我通过Nuget手动安装了Microsoft.EntityFrameworkCore.Relational包,也无法使用SqlQuery方法。

更新于:5个月前
赞一波!

文章评论

评论问答