[英]Passing empty string to EF6
This code runs fine in the SQL Server Management Studio: 这段代码可以在SQL Server Management Studio中正常运行:
SELECT [PassNumber] FROM [dbo].[Customers] WHERE [PassNumber] <> 'A'
This code also works as expected: 该代码也可以按预期工作:
string query = "PassNumber <> 'A'";
DbSqlQuery<Customer> data = db.Customers.SqlQuery( string.Format("select * from customers where {0}", query) );
Now it is changed to exclude empty rows and this code works fine on SSMS: 现在将其更改为排除空行,并且此代码在SSMS上可以正常工作:
SELECT [PassNumber] FROM [Customers] WHERE [PassNumber] <> ''
But I can't find a way to correctly format the query string. 但是我找不到正确格式化查询字符串的方法。 I have tried all possible combinations that I thought of, but the code throws an exception: "Incorrect syntax near the keyword '<>'."
我已经尝试过所有可能想到的组合,但是代码引发了异常:“关键字'<>'附近的语法不正确。”
string query = "PassNumber <> '' ";
DbSqlQuery<Customer> data = db.Customers.SqlQuery( string.Format("select * from customers where {0}", query) );
NOTE: For simplicity, the check for null value has been left out of the examples in the question. 注意:为简单起见,问题示例中未包含对空值的检查。
Why don't you use LINQ
when querying in EF
. 在
EF
查询时,为什么不使用LINQ
。 Then everything might be easier: 然后,一切可能会更容易:
var customerList = db.Customers.Where(c => c.PassNumber == string.Empty).ToList();
Have you tried to use 您是否尝试过使用
is null
clause on the SQL? SQL子句? Or
is not null
或
is not null
If you insist on doing this by raw SQL you should use: 如果您坚持通过原始SQL来执行此操作,则应使用:
db.Customers.SqlQuery("select * from customers where PassNumber <> @p0, string.Empty);
Or 要么
db.Customers.SqlQuery("select * from customers where LEN(PassNumber) > 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.