visc
visc

Reputation: 4959

Create entry if one does not exist

I'm trying to create a single instance of a model in my Db using Entity Core. The way I want it to work is, if the entry in the Db does not exist than make one. Instead of writing a getter method to do the work, is it possible to have Entity Core generate me a blank entry to work with and the save back?

I tried using FirstOrDefault to no avail.

Here is some sample code:

using (var context = new SearchTermInformationContext())
{
    // this very first line should return me the single instance or create one if it doesnt exist.
    var searchTermInfo = context.SearchTermInformation.FirstOrDefault();
    searchTermInfo.num_search_terms += numSearchTerms;
    searchTermInfo.offset = offset;
    searchTermInfo.last_updated += (DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond).ToString();
    await context.SaveChangesAsync(ct);
}

Upvotes: 0

Views: 512

Answers (1)

Jakotheshadows
Jakotheshadows

Reputation: 1515

FirstOrDefault() grabs the first element of an IEnumerable, and if the sequence is empty it returns the default value for that type. Since an Entity is always going to be a class, the default "value" for any class is null. There is no way to my knowledge to change this behavior. If you want this behavior, you will have to implement it yourself by creating a new instance of your type, filling in the fields, and performing an insert through your context. If you want to get really fancy, you might be able to make an extension method on DbSet<T> to perform an add of a blank instance and return the attached entity without saving changes.

Upvotes: 1

Related Questions