Entity Framework Core not adding records

c# entity-framework-core

Question

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

1
1
5/31/2019 4:18:36 PM

Popular Answer

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();
            }                
        }
0
5/31/2019 1:48:53 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow