使用Entity Framework进行批量插入/更新的高效方式 [英] Efficient way to do bulk insert/update with Entity Framework

查看:975
本文介绍了使用Entity Framework进行批量插入/更新的高效方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体列表,我想把它们插入一个数据库。如果实体已经存在于数据库中,那么它需要被跳过。如果它在数据库中但是具有不同的值,那么它需要更新。



除了每个数据库调用之外,还有什么办法可以做这个吗?



我的计划是尝试插入,如果抛出一个唯一的约束异常,然后执行更新。

解决方案

在这种情况下,请勿使用实体框架。只需使用一个存储过程(如何依赖于您使用EF的版本/方法,您可能必须扩展您的 DbContext 或添加实体模型中的映射)。



如果您使用SQL Server,那么在您的商店流程中,请使用 MERGE 命令,有效地完全需要什么:insert if it not exist,或更新,如果它。一切都在一个高效的SQL查询中。


I have a list of entities and I want to insert them into a database. If the entity already exists in the database as is then it needs to be skipped. If its in the database but with different values then it needs to be updated.

Is there any way to do this other than do a db call per item?

My plan is to try an insert, if a unique constraint exception on the key is thrown then do an update.

解决方案

Just don't use Entity Framework in this case. Just use a stored procedure (how to depends on the version/approach you use with EF, you might will have to extend your DbContext or add a mapping from the entity model).

If you're using SQL Server, then in your store procedure, do use the MERGE command that efficiently does exactly what you need: insert if it doesn't exist, or update if it does. Everything in a single, efficient SQL query.

这篇关于使用Entity Framework进行批量插入/更新的高效方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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