11

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(); 
} 
Cristian Diaconescu
  • 34,633
  • 32
  • 143
  • 233

1 Answers1

13

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.

Community
  • 1
  • 1
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • 2
    Correct, it wasn't designed for use outside of Migrations. – bricelam Jul 07 '15 at 15:47
  • So... how are you supposed to do it? – Izzy Dec 06 '16 at 16:54
  • As I said before, using the same idea @CristiDiaconescu shows at the end of her post. If your entity already has some id then is an update, otherwise, you need to add it – ocuenca Dec 06 '16 at 17:00
  • I know it's years later, but "whatever you supplied as a key (first parameter)" ... does that mean it treats whatever parameter happens to come first as the key, or does it use the actual key defined as such in the EF object? – CarenRose Jun 04 '20 at 19:16