Linq to sql中如何使用一个统一事务保存级联表格

需要使用到DataContext的嵌套

 

服务代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Configuration;

namespace CsharpTrainer.Linq.Service.Northwind
{
    public class CascadeTableService
    {
        public bool AddCascadeTables(CascadeA tableA, List<CascadeB> tablesB, List<CascadeC> tablesC)
        {
            bool result;
            
            try
            {
                using (DataContext context = new DataContext(ConfigurationManager.ConnectionStrings["NorthwindConnStr"].ToString()))
                {
                    using (NorthwindDBDataContext northwindContext = new NorthwindDBDataContext())
                    {
                        northwindContext.CascadeA.InsertOnSubmit(tableA);
                        northwindContext.CascadeB.InsertAllOnSubmit(tablesB);
                        northwindContext.CascadeC.InsertAllOnSubmit(tablesC);

                        northwindContext.SubmitChanges();
                    }

                }

                result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                result = false;
            }

            return result;
        }
    }
}

 

客户端测试代码如下:

Guid caId, cbId, ccId;
            
            caId = Guid.NewGuid();
            CascadeA tableA = new CascadeA
            {
                CaId = caId,
                CaContent = "Content A1"
            };
            
            List<CascadeB> tablesB = new List<CascadeB>();
            List<CascadeC> tablesC = new List<CascadeC>();
            CascadeB tableB;
            CascadeC tableC;
            for (int i = 1; i <= 3; i++)
            {
                cbId = Guid.NewGuid();
                tableB = new CascadeB
                {
                    CbId = cbId,
                    CaId = caId,
                    CbContent = "Content B" + i.ToString()
                };
                tablesB.Add(tableB);

                for (int j = 1; j <= 3; j++)
                {
                    ccId = Guid.NewGuid();
                    tableC = new CascadeC
                    {
                        CcId = ccId,
                        CbId = cbId,
                        CcContent = "Content C" + i.ToString() + j.ToString()
                        //CcContent = sb.ToString()
                    };
                    tablesC.Add(tableC);
                }
            }

            CascadeTableService service = new CascadeTableService();
            bool result = service.AddCascadeTables(tableA, tablesB, tablesC);
            if (result)
                Console.WriteLine("Add Cascade Tables Successfully!");
            else
                Console.WriteLine("Failed to add cascade tables!");

 

 

 

posted @ 2012-03-22 16:02  Master HaKu  阅读(385)  评论(0编辑  收藏  举报