使用Entity Framework进行批量插入/更新的高效方式 [英] Efficient way to do bulk insert/update with 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屋!