问题
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.
回答1:
In the above coding always returns NULL
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:
var allContacts = await dbContext.Contact.ToListAsync();
...or try to specify an id that you know for sure exists in the database:
var contact = await dbContext.Contact.FirstOrDefaultAsync(a => a.Id == 1);
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:
...
else
{
contactObj = new contactObj()
{
Id = 10,
FirstName = "John";
LastName = "Smith";
};
dbContext.Contact.Add(contactObj);
}
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.
Kindly assist me how to utilize this method using Asynchronously.
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
await dbContext.SaveChangesAsync();
来源:https://stackoverflow.com/questions/41098375/async-await-and-continuewith-for-a-entity-framework-database-process-method-in-c