Entity Framework Core GetOrAdd Method

asp.net-core entity-framework-core

Question

I'm working on a post method that should have a really good performance.

I have a value in the request body that will look in the database for the row that is connected with that value and return it and add it as a foreign key.

So how it is now:

  1. Look in the database and check if the data already exists
  2. If no add it to the database
  3. Look that added or already existing data in the database and join it to the entity

So now there are 3 calls to the database

I was wondering if there is some kind of GetOrAdd method that will connect the table to my data if it exists and if it not exists add it to the database so it will most of the time only have 1 call to the database instead of always 3 calls

1
2
11/28/2018 7:13:46 PM

Accepted Answer

Please read the following doc

Here is an "Insert or Update" pattern:

public void InsertOrUpdate(Blog blog)
{
    using (var context = new BloggingContext())
    {
        context.Entry(blog).State = blog.BlogId == 0 ?
                                   EntityState.Added :
                                   EntityState.Modified;

        context.SaveChanges();
    }
}

Of note, once you hit SaveChanges() you can expect your in memory object (blog, in this case) to be the same object that is stored in the database, and would not have to make a 3rd call to retrieve it again. EF Core will update the Primary Key with the actual persisted Id.

2
11/28/2018 2:04:54 PM

Popular Answer

using (var context = new BloggingContext())
{
   var blog = new Blog {Id = 1, Url = "blablabla" };
   context.Blogs.Update(blog);
   await context.SaveChangesAsync();
}

If a reachable entity has its primary key value set then it will be tracked in the Microsoft.EntityFrameworkCore.EntityState.Modified state. If the primary key value is not set then it will be tracked in the Microsoft.EntityFrameworkCore.EntityState.Add state.

This comment is from Entity Framework Core's Update method. You just need to call Update method if entity is exist in Database it will be updated otherwise will be created as new record.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow