我正在使用存储过程使用 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;
}
但我无法将结果传递到列表中。
无法创建抽象类或接口“IDbcommand”的实例。
如何通过 Idbconnection 使用 Idbcommand?
多谢,
AA