[英]Entity Framework: Passing String Parameter to FromSql Statement in Version 2.2
I am trying to pass a string parameter to a SQL Query, Receiving error below.我正在尝试将字符串参数传递给 SQL 查询,接收错误如下。 How can I resolve this?
我该如何解决这个问题? Currently utilizing answer EF Core 2.2, Passing String Parameter to FromSql Statement
当前使用答案EF Core 2.2,将字符串参数传递给 FromSql 语句
Input String was not in a correct format.
输入字符串的格式不正确。
public async Task<IEnumerable<Product>> GetProduct(string productKey)
{
var productParameter = new SqlParameter("@productKey", SqlDbType.VarChar);
productParameter.Value = productKey;
var productIdList = db.TestDb
.FromSql($"select ProductId from dbo.Product product" +
" (where product.ProductKey = {productParameter})" )
.Select(c => c.ProductId).ToList();
It is type varchar(6) from ProductKey它是 ProductKey 中的 varchar(6) 类型
Using Net Core 2.2使用网络核心 2.2
If you are using FromSql
you should construct your code like this to properly apply the SqlParameter:如果您使用
FromSql
,您应该像这样构建代码以正确应用 SqlParameter:
var productIdList = db.TestDb
.FromSql($"select ProductId from dbo.Product product where product.ProductKey = @productKey",productParameter )
.Select(c => c.ProductId).ToList();
Depending on the version of EF you are using, you could also use FromSqlInterpolated
instead of FromSql
and do away with the SqlParameter altoghter.根据您使用的 EF 版本,您还可以使用
FromSqlInterpolated
而不是FromSql
并取消 SqlParameter altoghter。
1) Query is not correct: you don't have FROM statement, which is required. 1)查询不正确:您没有 FROM 语句,这是必需的。 I presume that you wanted something like
我想你想要类似的东西
select productKey
from dbo.Product product
where product.Product = <paramName>
2) When using FromSQL: in the query string you have to input the name of the parameter, not the instance. 2) 使用 FromSQL 时:在查询字符串中,您必须输入参数的名称,而不是实例。 So change {productParameter} to @productKey
所以将{productParameter}更改为@productKey
3) Pass the SqlParameter instance as second argument to FromSql method. 3) 将 SqlParameter 实例作为第二个参数传递给 FromSql 方法。
var productParameter = new SqlParameter("@productKey", SqlDbType.VarChar);
productParameter.Value = productNumber;
var product= db.Tra
.FromSql($@"
select productKey
from dbo.Product product
where product.ProductKey = {productParameter.Name}", productParameter);
This might do the trick:这可能会奏效:
var productParameter = new SqlParameter("@productKey", productKey);
var productIdList = db.TestDb
.FromSql("select ProductId from dbo.Product where ProductKey = @productParameter",productParameter )
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.