ASP.NET help inserting data into normalized SQL tables best practice

◇◆丶佛笑我妖孽 提交于 2019-12-25 02:57:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!