![](/img/trans.png)
[英]LINQ to SQL and adding multiple records to foreign table for a single primary key
[英]Insert Records in multiple table which are dependent on primary / foreign key using Linq-to-SQL
我有3張桌子:
master_upload
(主上傳具有主鍵,其自動增量名為master_upload_id)
master_upload_files
(由2列組成,請參考上表中的master_upload_id)
master_upload_tags
(與秒相同)
在第二個和第三個表中,第一個表可以有多個行。
現在要插入第二張和第三張表,我需要一個master_upload_id
,我只有在插入后才能獲得。 因此,我必須至少調用db.SubmitChanges
3次。 如果第二和第三表有多個值,則必須為這兩個表中的每一行調用db.SubmitChanges
。 但是有時由於違反規則,第二張表或第三張表的插入可能會失敗。
因此,在這些情況下,我需要回退。 我怎樣才能做到這一點?
我以前是通過SQL Server存儲過程來做這些事情的,但是現在我需要在LINQ中做這件事。
// Here is my code sample
using (dbDataContext db = new dbDataContext())
{
db.master_uploads.InsertOnSubmit(mu);// toget mu.upload_id
try
{
db.SubmitChanges();
master_upload_file mf = new master_upload_file();
mf.master_upload_id = mu.upload_id;
mf.upload_file_id = uploadedfile.file_id;
db.master_upload_files.InsertOnSubmit(mf);
for (int i = 0; i < tags.Length; i++)
{
master_upload_tag mt = new master_upload_tag();
mt.master_upload_id = mu.upload_id;
mt.tag = tags[i];
db.master_upload_tags.InsertOnSubmit(mt);
}
db.SubmitChanges();
gtu.writetext("0",context);
}
catch (Exception)
{
gtu.writetext("1:File Upload Add Error", context);
}
}
我正在使用SQL Server 2008。
謝謝
您這樣做太復雜了! 用力,伙計! :-)
試試這個代碼:
// define your context
using (UploadContextDataContext ctx = new UploadContextDataContext())
{
try
{
// create your new upload
upload up = new upload();
up.UploadName = "Some test name";
// define two new upload files
UploadFile file1 = new UploadFile { FileName = "TestFile1.zip" };
UploadFile file2 = new UploadFile { FileName = "TestFile2.zip" };
// *ADD* those two new upload files to the "Upload"
up.UploadFiles.Add(file1);
up.UploadFiles.Add(file2);
// define three new upload tags
UploadTag tag = new UploadTag { TagName = "Tag #1" };
UploadTag tag2 = new UploadTag { TagName = "Tag #2" };
UploadTag tag3 = new UploadTag { TagName = "Tag #3" };
// *ADD* those three new upload tags to the "Upload"
up.UploadTags.Add(tag);
up.UploadTags.Add(tag2);
up.UploadTags.Add(tag3);
// add the "Upload" to the context - this *INCLUDES* the files and tags!
ctx.uploads.InsertOnSubmit(up);
// call SubmitChanges *just once* to store everything!
ctx.SubmitChanges();
}
catch (Exception exc)
{
string msg = exc.GetType().Name + ": " + exc.Message;
}
基本上,您將建立一個對象圖-基本的Upload
對象,然后將文件和標簽添加到該Upload
對象。 您只需要將該Upload
對象添加到數據上下文中,其他(添加的)子對象就會自動標記!
在這種情況下,你只需要調用SubmitChanges()
一個單一的時間 ,這將插入所有新對象,設置了所有必要的外鍵/主鍵關系和所有你。 無需擺弄主鍵,無需多次調用數據庫- 只需使用Linq-to-SQL的魔力!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.