Alex Alex -4 years ago 197
C# Question

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....

Answer Source

I found the answer:

if (preferences == null)
{
     preferences = new Preference() { UserId = user.Id };
     Context.Preferences.Add(preferences);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download