ASP.NET帮助插入数据规范化SQL表的最佳实践 [英] ASP.NET help inserting data into normalized SQL tables best practice

查看:98
本文介绍了ASP.NET帮助插入数据规范化SQL表的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个插入客户订单到我的SQL数据库的一个最常见的情况。我创建了一个分贝订单头和订单详细信息表,我试图插入一个头记录,并对应于头记录多个细节线(PK和FK约束是headerID)。

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).

目前,我插入我的头记录,然后查询分贝去年创建headerID,并使用该ID通过电网循环例如插入我的明细行。

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.

我知道这对插入记录规范化表一个笨方法,并有一个额外的SQL调用制成,这似乎是不必要的。因此,会有人知道一个更好的解决这个问题。

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.

推荐答案

我发现,使用实体框架解决了这个问题,而不进行任何额外的努力来搜寻最后插入headerid然后insertingit入细节表。所以,如果关系在实体框架明确,框架采用此工艺的照顾。例如:

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();
}

所以,只要所有的操作都​​在 rep.savechanges()之前完成; 主/详细数据将被正确地插入

So as long as all the operations are done before the rep.savechanges(); master/detail data will be inserted correctly.

如果然而,EF发现完整性错误或任何其他错误,没有数据将在所有插入的。

If however, EF finds an integrity error or any other errors, no data will be inserted at all.

所以这一个干净的方式接入主/从数据到SQL数据库。

So this a nice clean way to insert master/detail data into SQL database.

这篇关于ASP.NET帮助插入数据规范化SQL表的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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