[英]Entity Framework: Passing String Parameter to FromSql Statement in Version 2.2
我正在嘗試將字符串參數傳遞給 SQL 查詢,接收錯誤如下。 我該如何解決這個問題? 當前使用答案EF Core 2.2,將字符串參數傳遞給 FromSql 語句
輸入字符串的格式不正確。
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();
它是 ProductKey 中的 varchar(6) 類型
使用網絡核心 2.2
如果您使用FromSql
,您應該像這樣構建代碼以正確應用 SqlParameter:
var productIdList = db.TestDb
.FromSql($"select ProductId from dbo.Product product where product.ProductKey = @productKey",productParameter )
.Select(c => c.ProductId).ToList();
根據您使用的 EF 版本,您還可以使用FromSqlInterpolated
而不是FromSql
並取消 SqlParameter altoghter。
1)查詢不正確:您沒有 FROM 語句,這是必需的。 我想你想要類似的東西
select productKey
from dbo.Product product
where product.Product = <paramName>
2) 使用 FromSQL 時:在查詢字符串中,您必須輸入參數的名稱,而不是實例。 所以將{productParameter}更改為@productKey
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);
這可能會奏效:
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.