简体   繁体   English

实体框架核心未添加记录

[英]Entity Framework Core not adding records

I am trying to add a set of records with Entity Framework Core. 我正在尝试使用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. 当我观察调试器时,程序在进入FirstOrDefaultAsync调用时停止运行。 If I remove that, the program will run fine, but SaveChangesAsync still does not actually insert the records to the database. 如果删除它,该程序将运行正常,但是SaveChangesAsync仍然实际上不会将记录插入数据库中。

Could someone advise? 有人可以建议吗? Thanks 谢谢

Edit 1: 编辑1:

await DataWork(smallList);

Edit 2 RESOLUTION!: 编辑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. 控制台应用程序上的main方法不能真正异步。

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 当前, Add方法应为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();
            }                
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM