/// <summary> /// 测试 Identity 的处理. /// </summary> private static void TestIdeneity() { Console.WriteLine("===== 测试父子关系表的 Identity 的处理."); using (Test context = new Test(connString)) { test_Identity_tab testMainData = new test_Identity_tab() { value = "测试主" }; test_Identity_tab_Sub testSubData = new test_Identity_tab_Sub() { Value = "测试子" }; testSubData.test_Identity_tab = testMainData; // 插入. context.test_Identity_tab.InsertOnSubmit(testMainData); context.test_Identity_tab_Sub.InsertOnSubmit(testSubData); Console.WriteLine("Before SubmitChanges testMainData.id = {0}", testMainData.id); Console.WriteLine("Before SubmitChanges testSubData.id = {0}", testSubData.Id); context.SubmitChanges(); Console.WriteLine("After SubmitChanges testMainData.id = {0}", testMainData.id); Console.WriteLine("After SubmitChanges testSubData.id = {0}", testSubData.Id); } }
/// <summary> /// Linq2SQL 基本功能测试 /// /// 基本的 查询 / 插入 / 更新 / 删除 处理. /// /// </summary> private static void BaseTest() { Test context = new Test(connString); // 单表查询 var query = from testMain in context.TestMain select testMain; foreach (TestMain main in query) { Console.WriteLine("Main[{0}, {1}]", main.Id, main.Value); } // 关联查询 var query2 = from testSub in context.TestSub where testSub.TestMain.Value == "ONE" select testSub; foreach (TestSub sub in query2) { Console.WriteLine("Sub[{0}, {1}]", sub.Id, sub.Value); } // 插入. TestMain main3 = new TestMain(); main3.Id = 3; main3.Value = "Three"; context.TestMain.InsertOnSubmit(main3); context.SubmitChanges(); Console.WriteLine("INSERT FINISH! --- Please Press Enter Ket"); Console.ReadLine(); // 更新. var newTestMain = (from testMain in context.TestMain where testMain.Id == 3 select testMain).First(); newTestMain.Value = "Three3"; context.SubmitChanges(); Console.WriteLine("UPDATE FINISH! --- Please Press Enter Ket"); Console.ReadLine(); // 单表查询 TOP 2 var queryTop2 = (from testMain in context.TestMain orderby testMain.Id descending select testMain).Take(2); foreach (TestMain main in queryTop2) { Console.WriteLine("Main[{0}, {1}]", main.Id, main.Value); } // 删除. context.TestMain.DeleteOnSubmit(newTestMain); context.SubmitChanges(); Console.WriteLine("DELETE FINISH! --- Please Press Enter Ket"); Console.ReadLine(); }
/// <summary> /// 事务处理的测试. /// /// 隐式创建事务 /// /// </summary> private static void TransactionTest() { // 在我们没有显式的开启事务时, // DataContext.SubmitChanges在提交时会隐式创建事务 Test context = new Test(connString); try { // 插入. TestMain main3 = new TestMain(); main3.Id = 3; main3.Value = "Three"; context.TestMain.InsertOnSubmit(main3); TestMain main3x = new TestMain(); main3x.Id = 3; main3x.Value = "Three Err"; context.TestMain.InsertOnSubmit(main3x); context.SubmitChanges(); } catch (Exception err) { Console.WriteLine(err.ToString()); } var query = from testMain in context.TestMain where testMain.Id == 3 select testMain; Console.WriteLine("TestMain 表中, id=3 的记录有{0}条 ", query.Count()); }