0

I'm working on a WPF application and using SQLite database. I can do every CRUD operation with Entity Framework, but in some specific cases I have to use raw SQL queries, and sometimes it's not returning what I need.

Here is a sample code:

using (var db = new DbContext(AppIO.DatabaseFilePath)) {
    var key = 12;
    string sql = $"SELECT COUNT(*) FROM SomeTable WHERE SomeField={key}";
    var result = db.Database.ExecuteSqlCommand(sql);
}

I simplified the example. Here the result, what I got is -1. I copied the sql string value (after it's built) and executed in SQLiteStuido on the same database and it returned the correct value.

The DatabaseFilePath is correct. The connection is set correctly. I'm checking the same databases (in code and in SQLiteStudio). Any other idea?

2
  • 1
    I am pretty sure you need to use SqlQuery rather than ExecuteSqlCommand. Commented Feb 26, 2020 at 14:59
  • I tried it and it's working... thank you! Commented Feb 26, 2020 at 15:09

2 Answers 2

1

Try this:

var result = db.Database.SqlQuery<int>(sql).First();
Sign up to request clarification or add additional context in comments.

Comments

0

You have to call SqlQuery method and not ExecuteSqlCommand method. Since SqlQuery returns an IEnumerable you have to call Single. This is a the way to retreive scalar values from a query.

using (var db = new DbContext(AppIO.DatabaseFilePath)) {
    var key = 12;
    string sql = $"SELECT COUNT(*) FROM SomeTable WHERE SomeField={key}";
    var result = db.Database.SqlQuery<int>(sql).Single();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.