EF:在迁移之外使用DbSet< T> .AddOrUpdate()可以吗? [英] EF: Is it OK to use DbSet<T>.AddOrUpdate() outside of migrations?

查看:318
本文介绍了EF:在迁移之外使用DbSet< T> .AddOrUpdate()可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EntityFramework Migrations在 DbSet< T> 中提供一个扩展方法,特别是在迁移期间播种数据:

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);

这是安全的在常规代码中使用,即不是在迁移期间播种数据? / p>

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(); 
} 

似乎工作正常,但我想知道是否有任何缺点与传统独立实体相比,例如 on MSDN (文章的最后部分):

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(); 
} 


推荐答案

href =https://stackoverflow.com/users/471760/julie-lerman> Julie Lerman 谁是EF中的权威人士,您应该使用 AddOrUpdate 方法仅在迁移中,请查看此博客文章

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


这是在迁移期间用于播种数据。它看起来像
a很好的方法来添加进入你的应用程序,但这不是目的。

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

...

首先,它将执行一个查询在您的数据库中查找记录
,其中无论您提供的密钥(第一个参数)与
映射的列值(或值)匹配在 AddOrUpdate 。所以这个
是一个小的loosey-goosey匹配,但完美的种子
设计时间数据。

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.

这篇关于EF:在迁移之外使用DbSet&lt; T&gt; .AddOrUpdate()可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆