I have a Save
method to add/update a contact. I designed an asynchronous method. But I'm not able to get the records from the database.
Kindly have a look at the code:
public async Task<bool> SaveContact(Contact contact)
{
bool flag = false;
try
{
if(contact != null)
{
using(var dbContext = DBContext())
{
ContactEDB contactObj = new ContactEDB();
if(contact.Id > 0)
{
contactObj = await dbContext.Contact.FirstOrDefaultAsync(a => a.Id == contact.Id);
// The local variable "contactObj" always return NULL while on debugging
if(contactObj != null)
{
contactObj.FirstName = "John";
contactObj.LastName = "Smith";
}
}
else
{
contactObj = new contactObj()
{
FirstName = "John";
LastName = "Smith";
};
dbContext.Contact.Add(contactObj);
}
dbContext.SaveChanges();
}
}
}
catch(Exception ex)
{
// log error
}
return flag;
}
In the above code, it always returns NULL
if(contactObj != null)
{
contactObj.FirstName = "John";
contactObj.LastName = "Smith";
};
Kindly assist me anyone to fulfill the requirements.
Note: the said method is in a library. Kindly assist me how to utilize this method using asynchronously.
This means that there is no contact with an id equal to contact.Id present in the database. It has nothing do with whether you are using an async method to get the results from the database asynchronously.
You could temporarily try to fetch all records from the table:
...or try to specify an id that you know for sure exists in the database:
Use the debugger to determine the id of any contact returned from the first code line above and then use this id in the second query and you should get a contactObj object back.
Once you have confirmed that that you actually have some records in the database you can begin to examine the Contact object that you are passing to the SaveContact and determine why it doesn't have an id that exists in the database. Maybe you should set the Id property of a contactObj before you insert it into the database:
Also make sure that you fetch and add the same type of objects to your table. In the sample code you have posted there is three different types involved, Contact, ContactEDB and contactObj. It should probably only be one.
Apart from fetching records using the async overloads, you should also use the SaveChangesAsync method to perist the changes: https://msdn.microsoft.com/en-us/library/dn220070(v=vs.113).aspx