简体   繁体   English

实体框架创建FirstOrDefaultAsync添加新条目

[英]Entity framework create FirstOrDefaultAsync add new entry

I have the following code: 我有以下代码:

var preferences = await Context.Preferences.Where(x => x.UserId == user.Id).FirstOrDefaultAsync();

which checks the database to see if there is an entry in the preferences table that corresponds to the relevant userID 它检查数据库以查看首选项表中是否存在与相关userID相对应的条目

The situation I currently have is that there is no entry corresponding to this userID, so I check for null, as follows, and then create a new object: 我目前遇到的情况是,没有与此用户ID对应的条目,因此我按如下所示检查是否为空,然后创建一个新对象:

        if (preferences == null)
        {
            preferences = new Preference() { UserId = user.Id };
        } 

Then, further on int he code, all the changes are saved using this line: 然后,在进一步的代码中,所有更改都使用此行保存:

await Context.SaveChangesAsync();

which, as far as I understand, saves all changes made with the context object. 据我所知,它保存了上下文对象所做的所有更改。

The problem is that when preferences is null, the newly created object is not part of the context, so does not get saved. 问题是,当首选项为null时,新创建的对象不属于上下文,因此不会保存。

Is my understanding correct? 我的理解正确吗?

If so, how can I get this to save. 如果是这样,我如何保存它。

I have tried the following: 我尝试了以下方法:

if (preferences == null)
            {
                Context.Preferences = new Preference() { UserId = user.Id };
            }            

but that does not work (unsurprisingly). 但这是行不通的(毫不奇怪)。

I am sure this is quite simple, but I cannot see adn have not been able to find anything to help me.... 我相信这很简单,但是我看不到也找不到任何可以帮助我的东西。

I found the answer: 我找到了答案:

if (preferences == null)
{
     preferences = new Preference() { UserId = user.Id };
     Context.Preferences.Add(preferences);
}

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

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