我收到此错误:
System.Data.SqlClient.SqlException:'参数化查询'(@inputKarakterSoort varchar(8000))SELECT TOP 2 * FROM Karakter'需要未提供的参数'@inputKarakterSoort'。
但是我想我已经给出了参数化查询。
我的DAL:
public class SortedKarakterContext : ISortedKarakterContext
{
public string conn { get; set; }
public SortedKarakterContext()
{
this.conn = "MYCONNECTIONSTRING";
}
private SqlConnection GetConnection()
{
return new SqlConnection(conn);
}
public IEnumerable<KarakterDTO> GetSortedKarakters(string inputKarakterSoort)//User input was not supplied?? Hoe veranderen
{
using (SqlConnection connection = GetConnection())
{
connection.Open();
var command = new SqlCommand("SELECT TOP 2 * FROM Karakter WHERE KarakterSoort = @inputKarakterSoort ORDER BY NEWID();", connection);
command.Parameters.Add("@inputKarakterSoort", SqlDbType.VarChar).Value = inputKarakterSoort;
var reader = command.ExecuteReader();
var sortedKarakters = new List<KarakterDTO>();
while (reader.Read())
{
var karakter = new KarakterDTO
{
KarakterId = (int)reader["KarakterId"],
KarakterSoort = reader["KarakterSoort"]?.ToString(),
KarakterNaam = reader["KarakterNaam"]?.ToString()
};
sortedKarakters.Add(karakter);
}
return sortedKarakters;
}
}
}
}
我以为我是在这一行完成的:
command.Parameters.Add("@inputKarakterSoort", SqlDbType.VarChar).Value = inputKarakterSoort;
我确定inputKaraktersoort具有值,因为当我在其中放置断点时,它说它具有正确的值。
错误在此行上:
var reader = command.ExecuteReader();
有人可以帮助我吗?
根据请求,输入命令值和inputKarakterSoort:
当我键入此内容时:
inputKarakterSoort = "Defensive"
上方:connection.Open()
它确实有效,但是我想在查询中输入参数。
答案 0 :(得分:0)
我尝试了sgmoore的评论并实施了它。现在可以使用。
这是我的DAL:
public class SortedKarakterContext : ISortedKarakterContext
{
public string conn { get; set; }
public SortedKarakterContext()
{
this.conn = "MYCONNECTIONSTRING";
}
private SqlConnection GetConnection()
{
return new SqlConnection(conn);
}
public IEnumerable<KarakterDTO> GetSortedKarakters(string inputKarakterSoort)
{
using (SqlConnection connection = GetConnection())
{
connection.Open();
var command = new SqlCommand("SELECT TOP 2 * FROM Karakter WHERE KarakterSoort = @inputKarakterSoort ORDER BY NEWID();", connection);
if (inputKarakterSoort == null)
command.Parameters.Add("@inputKarakterSoort", SqlDbType.VarChar).Value = DBNull.Value;
else
command.Parameters.Add("@inputKarakterSoort", SqlDbType.VarChar).Value = inputKarakterSoort;
var reader = command.ExecuteReader();
var sortedKarakters = new List<KarakterDTO>();
while (reader.Read())
{
var karakter = new KarakterDTO
{
KarakterId = (int)reader["KarakterId"],
KarakterSoort = reader["KarakterSoort"]?.ToString(),
KarakterNaam = reader["KarakterNaam"]?.ToString()
};
sortedKarakters.Add(karakter);
}
return sortedKarakters;
}
}
}
}
答案 1 :(得分:-2)
代替使用
var command = new SqlCommand($“ SELECT TOP 2 * FROM Karakter WHERE KarakterSoort = {inputKarakterSoort} ORDER BY NEWID();”,connection);