c# - Inserting N child entities makes N queries. Bulk insert for child entities? -


i know can insert multiple entities using addrange() , make 1 trip database. in case i'm inserting single entity has, instance, 15 child entities. in case mini profiler says i'm doing 15 duplicate queries, afaik means takes 15 database trips no insert child entities.

question - how can bulk insert n child entities in 1 go? amount of data in entities incredibly small (few lines of text).

edit: having similar problem! looks there no way in ef. ended using sqlbulkcopy , except have manually add related (child) entities worked well. guys!

//data u want add db var data = somedata.tolist(); system.data.datatable table = new system.data.datatable();             table.columns.add("itemid", typeof(int));             table.columns.add("text", typeof(string));              table.columns.add("number", typeof(int));              table.columns.add("parentid", typeof(int));             foreach (var entity in data)             {                 datarow row = table.newrow();                 row["itemid"] = entity.someid;                 row["text"] = entity.sometext;                 row["number"] = entity.somenumber;                 row["parentid"] = entity.someparentid;                 table.rows.add(row);             }             using (sqlconnection cn = new sqlconnection(configurationmanager.connectionstrings["appdbcontext"].connectionstring))             {                 cn.open();                 using (sqlbulkcopy bulkcopy = new sqlbulkcopy(cn))                 {                     bulkcopy.destinationtablename = "someinputfields";                     bulkcopy.writetoserver(table);                 }                 cn.close();             }  

  • have profiles code?
  • how slow it?
  • is savechanges()?

if slow, best option be:

  1. insert parent no children , id.
  2. update child objects parent id
  3. bulkinsert of child entities using sqlbulkcopy

you need decide whether want go down optimizing or not.

from understanding every insert separate query in ef. if use addrange.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -