Пример #1
0
        /// <summary>
        /// 基本的 查询 / 插入 / 更新 / 删除 处理.
        /// </summary>
        private static void BaseTest()
        {
            TestEntities context = new TestEntities();
			// 单表查询
			var query =
				from testMain in context.test_main
				select testMain;
			foreach (test_main main in query)
			{
				Console.WriteLine("Main[{0}, {1}]", main.id, main.value);
			}

			// 关联查询
			var query2 =
				from testSub in context.test_sub
				where testSub.test_main.value == "ONE"
				select testSub;
			foreach (test_sub sub in query2)
			{
				Console.WriteLine("Sub[{0}, {1}]", sub.id, sub.value);
			}

			// 插入.
			test_main main3 = new test_main();
			main3.id = 3;
			main3.value = "Three";
			context.AddObject("test_main", main3);
			context.SaveChanges();

			Console.WriteLine("INSERT FINISH!");
			Console.ReadLine();

			// 更新.
			var newTestMain =
				(from testMain in context.test_main
				 where testMain.id == 3
				 select testMain).First();
			newTestMain.value = "Three3";
			context.SaveChanges();

			Console.WriteLine("UPDATE FINISH!");
			Console.ReadLine();

			// 单表查询 TOP 2
			var queryTop2 =
				(from testMain in context.test_main
				 orderby testMain.id descending
				 select testMain).Take(2);

			foreach (test_main main in queryTop2)
			{
				Console.WriteLine("Main[{0}, {1}]", main.id, main.value);
			}

			// 删除.
			context.DeleteObject(newTestMain);
			context.SaveChanges();

			Console.WriteLine("DELETE FINISH!");
			Console.ReadLine();
		}
Пример #2
0
        /// <summary>
        /// 事务处理测试.
        /// 
        /// 当调用 SaveChanges 时,如果当前事务存在,则对象服务将此事务用于对数据源进行的操作。
        /// 否则,将为操作创建新事务。
        /// 
        /// 可以使用 EntityTransaction、Transaction 或 TransactionScope 来定义事务。
        /// </summary>
        private static void TransactionTest()
        {

            TestEntities context = new TestEntities();


            // 插入.
            test_main main3 = new test_main();
            main3.id = 3;
            main3.value = "Three";
            context.AddObject("test_main", main3);

            // 插入.
            test_main main4 = new test_main();
            main4.id = 3;
            main4.value = "Three 4";
            context.AddObject("test_main", main4);

            try
            {
                context.SaveChanges();
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            }

            // 单表查询
            var query =
                from testMain in context.test_main
                where testMain.id == 3
                select testMain;


            Console.WriteLine("TestMain 表中, id=3 的记录有{0}条 ", query.Count());


        }