简体   繁体   中英

Why does my raw query to count rows always returns -1?

I'm trying to check if table exists, but not working correctly.

For some reason, count always returns -1. I already have a table in the database. It should return 1?

SearchEntities db = new SearchEntities();

var qry3 = "";
var sql4 = "SELECT Count(*) FROM SearchDB.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'portland'";
var count = db.Database.ExecuteSqlCommand(sql4);

ExecuteSqlCommand doesn't return data, it always returns an Int32 , which is the number of rows processed by the SQL script when it's a DDL/DML command.

You want SqlQuery<TElement>(String, Object[]) instead.

var count = db.Database.SqlQuery<int>(sql4).Single();

ExecuteStoreQuery Directly Execute Commands Against the Data Source.

int result = entity.ExecuteStoreQuery<int>(@"
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'TableName') 
    SELECT 1
ELSE
    SELECT 0
").SingleOrDefault();

See answer here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM