使用Linq-to-SQL在多个表中插入记录,这些记录依赖于主/外键

时间:2015-04-25 06:30:13

标签: c# sql-server database linq

我有3张桌子:

  1. master_upload(主上传包含主键,自动增量名为master_upload_id)

  2. master_upload_files(由2列组成,请参阅上表中的master_upload_id)

  3. master_upload_tags(与第二名相同)

  4. 在第2和第3个表中,第1个表可以有多行。

    现在要插入第2和第3个表格,我需要master_upload_id,我只能在插入后获得。因此我不得不至少打电话给db.SubmitChanges 3次。如果第二个和第三个表有多个值,我必须为这两个表中的每一行调用db.SubmitChanges。但有时候,由于某些规则违规,第2或第3表中的插入可能会失败。

    因此我需要在这些情况下回滚。我怎么能这样做?

    我用来通过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。

    由于

1 个答案:

答案 0 :(得分:0)

你这样做太复杂了!使用武力,伙计!! : - )

试试这段代码:

// 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的魔力!