Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF: Is it OK to use DbSet<T>.AddOrUpdate() outside of migrations?

EntityFramework Migrations provides an extension method on DbSet<T>, specifically for seeding data during a migration:

void AddOrUpdate<TEntity>(this IDbSet<TEntity> set, params TEntity[] entities);

Is this safe to use in "regular" code, i.e. not for seeding data during a migration ?

var blog = ...//detached instance from a request

using (var context = new BloggingContext()) 
{ 
    context.Blogs.AddOrUpdate(blog); 
    context.SaveChanges(); 
} 

It seems to work fine, but I'm wondering if it has any downsides compared to the "traditional" 'detached entity' sceario - as described, for instance, on MSDN (last part of the article):

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

    context.SaveChanges(); 
} 
like image 663
Cristian Diaconescu Avatar asked Jul 07 '15 15:07

Cristian Diaconescu


1 Answers

Well, according to Julie Lerman who is an authority in EF, you should use AddOrUpdate method only in migrations, check this blog post:

"It is meant for use with seeding data during migrations.It looks like a nice method to add into your apps but that’s not it’s purpose."

...

First, it will execute a query in your database looking for a record where whatever you supplied as a key (first parameter) matches the mapped column value (or values) supplied in the AddOrUpdate. So this is a little loosey-goosey for matching but perfectly fine for seeding design time data.

As you can see, it has an additional cost because, before add or update, it executes an query searching if the record already exist. So, the best way is use the code you mention at the end of your post.

like image 72
octavioccl Avatar answered Oct 03 '22 16:10

octavioccl