.Net如何使用命令文本而不是调用存储过程并将其存储在具有IDbConnection的列表中

时间:2018-02-01 09:27:59

标签: c# sql .net stored-procedures idbcommand

我使用存储过程使用IDbconnection从Sql数据库获取结果。作为使用存储过程的替代方法,在代码中执行查询的其他选项是什么?

如果我使用存储过程,每台机器都必须拥有它,如果用户删除/更改存储过程,应用程序将不会运行,那么执行SQL语句的最佳方式是什么(如文本)?

例如,我调用存储过程,然后将结果放入列表中。

 public List<BestMatchModel> GetBestMatchBooks() 
        List<BestMatchModel> output;
        using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.GetCnnstring()))
        {
            var p = new DynamicParameters();
            output = connection.Query<BestMatchModel>("dbo.spGetBestMatchBooks", p, commandType: CommandType.StoredProcedure).ToList();
        }
        return output;
    }

如何将commandText用于上述代码?

这是sql语句,我将其保存为存储过程dbo.spGetBestMatchBooks。

select ba2.[BookID] as b2BookiD ,ba2.[Cupboard], bl2.[Rank] as b2Rank,ba.[BookID] as b1BookiD,ba.[Shelf],bl.[Rank] as b1Rank FROM [dbo].[Book_Arrange] ba,[dbo].[Book_Arrange] ba2, [dbo].[Book_List] bl, [dbo].[Book_List] bl2 WHERE ba.BookID = bl.BookID and ba2.BookID = bl2.BookID and ba.ArrangeDate IS NOT NULL and ba2.ArrangeDate IS NOT NULL and ba.[Shelf] IS NOT NULL and ba2.[Cupboard] IS NOT NULL and ba.BookID <> ba2.BookID and bl.[Selected] ='yes' and bl2.[Selected] ='yes' order by bl.[Rank],bl2.[Rank]

我尝试使用Idbcommand而不是存储过程。

public List<BestMatchModel> GetBestMatchBooks()
    {
        string commandText = "select ba2.[BookID] as b2BookiD ,ba2.[Cupboard], bl2.[Rank] as b2Rank" +
                              ", ba.[BookID] as b1BookiD,ba.[Shelf],bl.[Rank] as b1Rank" +
                              " FROM [dbo].[Book_Arrange] ba,[dbo].[Book_Arrange] ba2, [dbo].[Book_List] bl, [dbo].[Book_List] bl2 " +
                              " WHERE ba.BookID = bl.BookID and ba2.BookID = bl2.BookID " +
                              " and ba.ArrangeDate IS NOT NULL" +
                              " and ba2.ArrangeDate IS NOT NULL" +
                              " and ba.[Shelf] IS NOT NULL" +
                              " and ba2.[Cupboard] IS NOT NULL" +
                              " and ba.BookID<> ba2.BookID" +
                              " and bl.[Selected] = 'yes'" +
                              " and bl2.[Selected] = 'yes'" +
                              " order by bl.[Rank], bl2.[Rank]";
        List<BestMatchModel> output;
        using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.GetCnnstring()))
        {
            IDbCommand command = connection.CreateCommand();
            command.CommandText = commandText;
            var p = new DynamicParameters();
            output =  command.ExecuteScalar()<BestMatchModel>;
        }
        return output;
    }

但我无法将结果传递到列表中。

无法创建抽象类或接口的实例&#39; IDbcommand&#39;。

如何使用Idbcomction使用Idbcommand?

非常感谢,

AA

0 个答案:

没有答案