问题
Hi i have a most common situation of inserting a client order into my SQL database. I have created an order header and order detail tables in the db and i am trying to insert a single header record and multiple detail lines corresponding to that header record (the PK and FK constraint is the headerID).
Currently, i insert my header record, then query the db for last created headerID and use that ID to insert my detail lines by looping through grid for example.
I know this is a stupid way for inserting records into normalized tables and there is an extra sql call made, which seems unnecessary. Therefore, would anyone know of a better solution to this problem.
回答1:
I found that using Entity Framework solves this problem, without making any extra effort to search for the last insert headerid and then insertingit into the detail table. So if relationships are well defined in the Entity Framework, the framework takes care of this process. For Example:
using (var rep = new Repo()){
Header hd = new Header();
hd.name = "some name";
Detail dt = new Detail();
dt.itemname = "some item name";
hd.Details.Add(dt);
rep.Headers.Add(hd);
rep.savechanges();
}
So as long as all the operations are done before the rep.savechanges();
master/detail data will be inserted correctly.
If however, EF finds an integrity error or any other errors, no data will be inserted at all.
So this a nice clean way to insert master/detail data into SQL database.
来源:https://stackoverflow.com/questions/29087134/asp-net-help-inserting-data-into-normalized-sql-tables-best-practice