I know I can insert multiple entities using AddRange() and it will only make one trip to the database. In my case I'm inserting a single entity which has, for instance, 15 child entities. In this case Mini Profiler says I'm doing 15 duplicate queries, which afaik means that it takes 15 database trips no insert the child entities.
Question is - how can I bulk insert N child entities in one go? The amount of data in entities is incredibly small (few lines of text).
EDIT: For anyone having similar problem! Looks like there is no way to do so in EF. I ended up using SqlBulkCopy and except that you have to manually add related (child) entities it worked very well. Thanks guys!
//data u want to add to 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();
}