I am trying to add a set of records with Entity Framework Core. For some reason I cannot get the records to actually save to the database.
Below is the code running. There are not exceptions thrown.
using (var context = new UserEntity.UsersContext())
{
foreach(var u in users)
{
var tempUser = await context.User.FirstOrDefaultAsync(x => x.Username == u.Username);
if (tempUser == null)
{
context.Add(u);
}
await context.SaveChangesAsync();
}
}
When I watch the debugger, the program stops running when it gets to the FirstOrDefaultAsync
call. If I remove that, the program will run fine, but SaveChangesAsync
still does not actually insert the records to the database.
Could someone advise? Thanks
Edit 1:
await DataWork(smallList);
Edit 2 RESOLUTION!:
This is completely my fault from over looking the fact that this is a console app, as it is going to be used once and never seen again. The main method on a console app cannot be truly asynchronous.
My solution below:
MyAsyncMethod().Wait();
That's it. It works after this. Thank you all for spending the time to try to help me, it pushed me in the right direction
You are currently mixing async and non async calls. Currently the Add methods should be AddAsync
If you want async operation your code should be :
using (var context = new UserEntity.UsersContext())
{
foreach(var u in users)
{
var tempUser = await context.User.FirstOrDefaultAsync(x => x.Username == u.Username);
if (tempUser == null)
{
await context.AddAsync(u);
}
await context.SaveChangesAsync();
}
}