介绍
最近比较关注Entity framework,之前只是略有了解,没有自己动手搭建过应用程序,于是创建一个简单的应用程序试用一下,感觉用起来很舒服,呀,原来这么神奇,在不用使用sql语句的情况下,数据已经悄悄地进入数据库了。 先把这个简单的小例子重现一下,更进一步的东西,日后消化理解后在整理出来。
正文
在开始之前先交代下开发环境,VS2010与SQL2008作为例子的开发环境。
1 先创建一个数据库AUTOLOT 创建一张表
1 CREATE TABLE [dbo].[Inventory](
3 [ Make ] [ nvarchar ] ( 50 ) NULL ,
4 [ Color ] [ nvarchar ] ( 50 ) NULL ,
5 [ PetName ] [ nvarchar ] ( 50 ) NULL ,
6 CONSTRAINT [ PK_Inventory ] PRIMARY KEY CLUSTERED
7 (
8 [ CarID ] ASC
9 ) WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ]
10 ) ON [ PRIMARY ]
11
12 GO
2 新建控制台应用程序
在解决方案中添加添加一个EDMX文件名InvertoryEDM.edmx
选择Entity Data Model
选择第一项,一路next下去。
到最后一步选Inventory表,然后完成。
添加完成后会如上图,将Inventory 重名为Car,PetName 重命名 CarNickname,一个Entity Data Model 就添加完成。
3 在控制台应用程序调用刚添加好的类。
1 static void Main(string[] args)
3 Console.WriteLine( " ***** Fun with ADO.NET EF ***** " );
4 AddNewRecord();
5 PrintAllInventory();
6 Console.ReadLine();
7 }
8 private static void AddNewRecord()
9 {
10 // Add record to the Inventory table of the AutoLot
11 // database.
12 using (AotuLotEntities context = new AotuLotEntities())
13 {
14 try
15 {
16 // Hard code data for a new record, for testing.
17 context.Cars.AddObject( new Car()
18 {
19 CarID = 2222 ,
20 Make = " Yugo " ,
21 Color = " Brown "
22 });
23 context.SaveChanges();
24 }
25 catch (Exception ex)
26 {
27 Console.WriteLine(ex.InnerException.Message);
28 }
29 }
30 }
31
32 private static void PrintAllInventory()
33 {
34 using (AotuLotEntities context = new AotuLotEntities())
35 {
36 foreach (Car c in context.Cars)
37 Console.WriteLine(c);
38 }
39
40 }
运行完程序后,查看数据库会有一条新增记录。
更新于删除的代码如下
1 private static void UpdateRecord()
3 // Find a car to delete by primary key.
4 using (AotuLotEntities context = new AotuLotEntities())
5 {
6 // Define a key for the entity we are looking for.
7 EntityKey key = new EntityKey( " AutoLotEntities.Cars " , " CarID " , 2222 );
8 // Grab the car, change it, save!
9 Car carToUpdate = (Car)context.GetObjectByKey(key);
10 if (carToUpdate != null )
11 {
12 carToUpdate.Color = " Blue " ;
13 context.SaveChanges();
14 }
15 }
16 }
17
18 private static void RemoveRecord()
19 {
20 // Find a car to delete by primary key.
21 using (AotuLotEntities context = new AotuLotEntities())
22 {
23 // Define a key for the entity we are looking for.
24 EntityKey key = new EntityKey( " AutoLotEntities.Cars " , " CarID " , 2222 );
25 // See if we have it, and delete it if we do.
26 Car carToDelete = (Car)context.GetObjectByKey(key);
27 if (carToDelete != null )
28 {
29 context.DeleteObject(carToDelete);
30 context.SaveChanges();
31 }
32 }
33 }
小结
通过上面介绍,可以创建一个简单使用Entity framework作为持久层的应用程序,实现数据的增删改等操作。
在设计上或者原理上理解EF,更多的请参考 EntityFramework之领域驱动设计实践