[英]Linq query FromSql where passing string value
Have a SQL table example column Id-Pk-int, Name-varchar(250), ...有一个 SQL 表示例列 Id-Pk-int, Name-varchar(250), ...
Using EF Core使用 EF 核心
when I execute当我执行
var data= (from c in _db.Table.FromSql($"select * from Emp where id=1")
select c).FirstOrDefault();
returns successfully成功返回
but when I execute using where clause name (string)但是当我使用 where 子句名称(字符串)执行时
var data = (from c in _db.Table.FromSql($"select * from Emp where Name=Mike")
select c).FirstOrDefault();
I get an exception, System.Data.SqlClient.SqlException: 'Invalid column name 'Mike'.'我得到一个异常,System.Data.SqlClient.SqlException:'无效的列名'Mike'。
I tested if I changed the data in the database column: Name to 123 (number) it works but fails when value is string我测试了我是否更改了数据库列中的数据: Name to 123 (number) it works but failed when value is string
I think the problem is occured because of you forgot to use '
symbol.我认为问题是因为您忘记使用'
符号而发生的。 Because exception says there is no column named Mike.因为异常说没有名为 Mike 的列。 And column name should be "Name" as i see from the code.正如我从代码中看到的那样,列名应该是“名称”。
Check if Name
column is VARCHAR
.检查Name
列是否为VARCHAR
。 If the column is VARCHAR
you need use ' symbols.如果列是VARCHAR
,则需要使用 ' 符号。 If not you can use like WHERE ID=1
如果没有,您可以使用WHERE ID=1
Use that;使用那个;
var data = (from c in _db.Table.FromSql($"select * from Emp where Name='Mike'")
select c).FirstOrDefault();
Edit 2: I see that you said Id-int, Name-varchar.编辑2:我看到你说Id-int,Name-varchar。 Can you use the code i wrote?你能用我写的代码吗? Thanks.谢谢。
You should use proper parameterization, do not concatenate or interpolate data into a query, or you will leave yourself open to injection attacks and syntax errors.您应该使用适当的参数化,不要将数据连接或插入到查询中,否则您将面临注入攻击和语法错误。
var data = (from c in _db.Table.FromSql("select * from Emp where Name = @name",
new SqlParameter("@name", SqlDbType.VarChar, 50){Value = "Mike"})
select c).FirstOrDefault();
var data = (from c in _db.Table.FromSql("select * from Emp where Id = @id",
new SqlParameter("@id", SqlDbType.Int){Value = 1})
select c).FirstOrDefault();
In newer versions of EF Core, use FromSqlRaw
in the same way.在较新版本的 EF Core 中,以相同方式使用FromSqlRaw
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.