使用实体框架进行批量插入/更新的有效方法 [英] Efficient way to do bulk insert/update with Entity Framework

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

问题描述

我有一个实体列表,我想将它们插入到数据库中.如果实体已按原样存在于数据库中,则需要跳过它.如果它在数据库中但具有不同的值,则需要对其进行更新.

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.

推荐答案

在这种情况下不要使用实体框架.只需使用存储过程(如何使用取决于您使用 EF 的版本/方法,您可能需要扩展您的 DbContext 或从实体模型添加映射).

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

如果您使用的是 SQL Server,那么在您的存储过程中,请使用 MERGE 命令可以有效地完全满足您的需要:如果不存在则插入,如果存在则更新.一切都在一个高效的 SQL 查询中.

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.

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

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