使用实体框架批量插入/更新 [英] Batch insert/update with entity framework

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

问题描述

  1. 我有一个标记"表,其表仅由ID和Name(唯一)组成.现在,从GUI用户可以为BlogPost输入标签.保存数据后,将标签存储在字符串(名称)数组中,我想将名称尚不存在的标签添加到Tag表中,并忽略名称已存在的标签并获取所有标签实体的列表(包括现有的和新添加的).如何仅用一次SQL往返就可以在Entity Framework中做到这一点?

  1. I have a Tags table whose schema consists of only ID and Name (unique). Now, from the GUI user can enter tags for a BlogPost. When the data is saved, with tags stored in an array of string (names), I want to add tags whose names don't yet exist to the Tag table and ignore tags whose names already exist AND get back the list of all tag entities (including the existing and newly added ones). How can I do this in Entity Framework in just 1 SQL roundtrip?

对于返回的标签,我想将它们与要添加的BlogPost对象相关联(该对象只是被实例化,尚未通过EF存储在DB中).

For the returned tags, I want to associate them to the to-be-added BlogPost object (which is just instantiated and not stored in DB via EF yet). Is it still possible that this step can be combined with #1 in 1 single roundtrip or must I have to issue another query?

推荐答案

我不认为Entity Framework根本不进行批量插入(目前).因此,如果必须将数据库往返次数保持在如此低的水平,则可能必须使用存储过程或数据库触发器.幸运的是,实体框架支持返回实体类型的存储过程.在MSDN上有关于此的文档.您可以创建一个proc,该proc接受标签的字符串列表并返回标签实体实例.另外,您可以在帖子表中添加VARCHAR列以获取标记的定界列表,然后在触发器中对其进行解析.

I don't believe the Entity Framework does batch inserts at all (at present). So if you must keep the number of DB roundtrips so low, you're probably going to have to use a stored procedure or a database trigger. Fortunately, the Entity Framework supports stored procedures which return entity types. There is documentation on MSDN about this. You could create a proc which accepts a string list of tags and returns tag entity instances. Alternately, you could add a VARCHAR column to your post table for a delimited list of tags, and parse it in the trigger.

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

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