一个使用EF进行查改的样例

 数据库管理软件是MS SQL,数据库是微软的NorthWind。

主体代码,完整的解决方案见最下方

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace TestCodeFirst
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             ValidaProduct();
13             UpdateProduct();
14             GetSpecialProduct();
15         }
16 
17         private static void ValidaProduct()
18         {
19             using (Northwind northwind = new Northwind())
20             {
21                 var product = northwind.Products.Find(1);
22                 Console.WriteLine(string.Format("product.Name{0} product.UnitPrice:{1}", product.ProductName, product.UnitPrice));
23                 product.ProductName = null;
24                 product.UnitPrice = 2.33M;
25                 product.Discontinued = false;
26                 northwind.SaveChanges();
27             }
28         }
29 
30         private static void UpdateProduct()
31         {
32             using (Northwind northwind = new Northwind())
33             {
34                 var product = northwind.Products.Find(1);
35                 Console.WriteLine(string.Format("product.Name{0} product.UnitPrice:{1}",product.ProductName, product.UnitPrice));
36                 product.UnitPrice = 2.33M;
37                 product.Discontinued = false;
38                 northwind.SaveChanges();
39 
40                 var product2 = northwind.Products.Find(1);
41                 Console.WriteLine(string.Format("product.Name{0} product.UnitPrice:{1}", product.ProductName, product2.UnitPrice));
42             }
43         }
44 
45         private static void GetSpecialProduct()
46         {
47             using (Northwind northwind = new Northwind())
48             {
49                 var product = from p in northwind.Products
50                               where p.Category.CategoryName == "Beverages"
51                               select p;
52                 foreach (var item in product)
53                 {
54                     Console.WriteLine(string.Format("ProductName:{0}", item.ProductName));
55                 }
56                 Console.WriteLine(string.Format("执行结果:{0}", product == null));
57             }
58         }
59     }
60 }


完整下载

posted @ 2013-01-04 12:58  陈哈哈  阅读(218)  评论(0编辑  收藏  举报