如何使用 EF Core 执行 RAW SQL 查询?

Dan*_*edo 5 c# entity-framework-core asp.net-core

基本上我遇到的问题是我想在数据库中运行一个查询,它不是我的模型的表示。

这是我创建与另一个数据库的连接的代码:

public static OtherContext GetNewContextGeneric(string connectionString)
        {
            var builder = new DbContextOptionsBuilder();
            builder.UseSqlServer(connectionString);

            OtherContext db = new OtherContext(builder.Options);

            return db;
        }
Run Code Online (Sandbox Code Playgroud)

这是我执行查询的代码:

public List<IQueryble> Query (string connectionString, string query)
        {
            try
            {
                using(var contextGeneric = ContextFactory.GetNewContextGeneric(connectionString))
                {
                    //I want something like this
                    return contextGeneric.Query(query).ToList();
                }
            }
            catch(System.Data.SqlClient.SqlException ex)
            {
                throw new SQLIncorrectException(ex);
            }
            catch(System.InvalidOperationException ex)
            {
                throw new NotImplementedException();
            }   
        }
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗?

Pro*_*log 3

您可以使用DbDataReader

using (var command = context.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "SELECT * From Make";
    context.Database.OpenConnection();
    using (var reader = command.ExecuteReader())
    {
        // Do something with result
        reader.Read(); // Read first row
        var firstColumnObject = reader.GetValue(0);
        var secondColumnObject = reader.GetValue(1);

        reader.Read(); // Read second row
        firstColumnObject = reader.GetValue(0);
        secondColumnObject = reader.GetValue(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里您可以了解更多如何从中读取值DbDataReader

或者,您可以使用FromSql()方法,但这仅适用于DbSet某些实体的预定义,这不是您想要的解决方案。