Operator '! = 'Cannot be applied to operands of type' Task 'and' int '

I recently started building Android apps using Xamarin. I am trying to create a small local database with SQLite. I used the following tutorial from the Xamarin documentation site .

Sorry, I get an error message:

Error CS0019: Operator '! = 'cannot be applied to operands of type "Task" and "int" (CS0019)

My code is as follows:

private string createDatabase(string path) { try { var connection = new SQLiteAsyncConnection(path);{ connection.CreateTableAsync<Person>(); return "Database created"; } } catch (SQLiteException ex) { return ex.Message; } } private string insertUpdateData(Person data, string path) { try { var db = new SQLiteAsyncConnection(path); if ( db.InsertAsync(data) != 0) db.UpdateAsync(data); return "Single data file inserted or updated"; } catch (SQLiteException ex) { return ex.Message; } } private int findNumberRecords(string path) { try { var db = new SQLiteConnection(path); // this counts all records in the database, it can be slow depending on the size of the database var count = db.ExecuteScalar<int>("SELECT Count(*) FROM Person"); // for a non-parameterless query // var count = db.ExecuteScalar<int>("SELECT Count(*) FROM Person WHERE FirstName="Amy"); return count; } catch (SQLiteException ex) { return -1; } } 

And the Person class is as follows:

 using System; using SQLite; namespace HelloWorld { public class Person { [PrimaryKey, AutoIncrement] public int ID { get; set; } public string FullName { get; set; } public string CarLicense { get; set; } public override string ToString() { return string.Format("[Person: ID={0}, FullName={1}, CarLicense={2}]", ID, FullName, CarLicense); } } } 

Can someone help me with this error?

+7
android c # sqlite xamarin xamarin.android
source share
5 answers

You can do it as follows:

 if ( (await db.InsertAsync(data)) != 0) 

Also see this answer for reasons why await often prefer to use .Result .

+7
source share

Instead of using Result , which can cause a lock to lock, you should wait for the result:

 if (await db.InsertAsync(data) != 0) { await db.UpdateAsync(data); } 

This requires your method to be asynchronous as well, so the signature should read:

 private async Task<string> insertUpdateData(...) 
+4
source share

This tells you that you need to compare the result, not the task. Update this line:

 if ( db.InsertAsync(data) != 0) 

to

 if ( db.InsertAsync(data).Result != 0) 
+2
source share

You can use async, wait if you want innsertUpdateData to be asynchronous.

 private async Task<string> insertUpdateData(Person data, string path) { try { var db = new SQLiteAsyncConnection(path); if ( 0 != await db.InsertAsync(data)) await db.UpdateAsync(data); return "Single data file inserted or updated"; } catch (SQLiteException ex) { return ex.Message; } } 
+2
source share

You need to add .result to db.InsertAsync (data)

+1
source share

All Articles