简体   繁体   中英

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

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:

        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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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