Entity Framework4.2 (十)CodeFirst(EF4 .2的Code First方法)(转)

长假归来,祝大家:龙年吉祥,龙马精神;福旺财旺事业旺,旺上加旺!!

差不多一个月没登录博客园了,呵呵。非常抱歉啦。

好了,闲言少叙,书归正传。呵呵。

==================================================

前面我有写过一篇《Entity Framework4.0 (三)概述(EF4 的Code First方法)》,目的是为了演示一下CodeFirst是怎么一回事。文章中的写法有些过时了,所以并不是项目中的推荐做法(Best Practice)。因为,现在我们使用功能更为完整的EF4.2的CodeFirst方法。

下面我们就开始喽!

说明:我们有两种方式添加EntityFramework.dll的引用:

1)使用NuGet将自动添加的是最新版本的EntityFramework 就是EF4.2的Dll。

 EF4.2和EF4.1的区别就是修改了一个Bug: 详情参考:http://blogs.msdn.com/b/adonet/archive/2011/11/01/ef-4-2-released.aspx

2)手动添加本地EntityFramework.dll引用的话,只能添加EF4.1而不是EF4.2,所以要下载安装EntityFramework41RC.下载地址:http://www.microsoft.com/download/en/details.aspx?id=18504

 因为使用EF4.2的dll,所以我们先简单介绍在VS2010中的小插件Nuget的使用(它可以帮助我们引入 EntitiFramework.dll),并且我们有了NuGet的帮助,就没有必要下载安装EntityFramework41RC,更不必要安装更 老的EF版本的CTP了(但是我以自己的血的教训建议你不要试图卸载之前版本的EntityFramework的CTP或RC,因为那样有可能会引起你 的.Net Framework 或 VS2010出现问题滴)

说明:你也可以不安装这个很Cool的工具(但是那样你就只能手动添加EF4.1的dll了)

安装完成以后,为了安全起见,最好重启下VS2010.

打开一个NuGet的命令行窗体,如果显示:

Type 'get-help NuGet' to see all available NuGet commands.

表示安装Nuget成功。

如果你使用的是Xp SP3的操作系统,有可能因为缺少Power shell2.0而提示出错。

此时只需要安装Power Shell2.0即可:地址http://support.microsoft.com/kb/968929,在页面的中下部,找到适合自己机器操作系统的Windows Management Framework ,下载并安装。然后重启VS2010.

(如果在安装power shell2.0的时候,提示power shell不兼容错误时是因为之前机器装有PowerShell1.0.此时解决办法是打开“控制面板”的“添加删除程序”,注意:需要选中“显示更新” 复选框才能看到PowerShell1.0,让后删除powershelll 1.0,再安装2.0即可)

3.新建咱们的Code First 解决方案:

File->New ->Project... 选择C# 的Console Application .命名为:EF41CodeFirstDemo

a)如果你在前面没有安装NuGet的话,可以在项目的References上右键,手动添加.NET标签下的EntityFramework引用.

b)如果你已经成功安装NuGet的话,在Packager Manager Console里面输入:install-package entityframework (注意:命令行内容不区分大小写滴,呵呵),此时NuGet到它的package库中下载并安装最新的EntityFramework.dll,手动的 话,你是安装本地的EntityFramework.dll,因为前面安装过了EntityFramework RC了。

在Program.cs中添加如下代码:

Program.cs
  1  using System;
  2  using System.Collections.Generic;
  3  using System.Linq;
  4  using System.Text;
  5  using System.Data.Entity;
  6  using System.ComponentModel.DataAnnotations;
  7  
  8  namespace EF41CodeFirstDemo
  9  {
 10      class Program
 11      {
 12          static void Main(string[] args)
 13          {
 14              Random random = new Random();
 15  
 16              using (MyContext context = new MyContext())
 17              {
 18                  Class cl = new Class();
 19                  cl.ClassName = "ClassName" + random.Next();
 20  
 21  
 22                  Course c1 = new Course() { CourseName = "course1Name" + random.Next() };
 23                  Course c2 = new Course() { CourseName = "course2Name" + random.Next() };
 24                  Course c3 = new Course() { CourseName = "course3Name" + random.Next() };
 25  
 26                  Student student = new Student();
 27                  student.StudentName = "Studentname" + random.Next();
 28                  student.Addre = new Address {StreetNumber=111,StreetName="address"+random.Next() };
 29                  student.DeliverAddre = new Address { StreetNumber = 222, StreetName = "deladdress" + random.Next() };
 30                  student.Courses.Add(c1);
 31                  student.Courses.Add(c2);
 32                  student.Courses.Add(c3);
 33  
 34                
 35  
 36                  cl.Students.Add(student);
 37  
 38                  context.Classes.Add(cl);
 39            
 40  
 41                  context.SaveChanges();
 42              }
 43          }
 44      }
 45  
 46      public class MyContext : DbContext
 47      {
 48          public DbSet<Student> Students {get;set; }
 49          public DbSet<Class> Classes{get;set;}
 50  
 51          public MyContext()
 52          {
 53              this.Configuration.LazyLoadingEnabled = true;
 54              Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
 55          }
 56        
 57  
 58          protected override void OnModelCreating(DbModelBuilder modelBuilder)
 59          {
 60              base.OnModelCreating(modelBuilder);
 61              //modelBuilder.Entity<Student>().ToTable("efdemo.StudentTable");
 62  //modelBuilder.Entity<Student>().Property(x => x.StudentID)
 63  //    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
 64  //    .IsRequired()
 65  //    .HasColumnName("TheStudentID");
 66  
 67  //modelBuilder.Entity<Student>().Property(x => x.StudentName)
 68  //    .IsRequired()
 69  //    .HasMaxLength(128)
 70  //    .HasColumnName("TheStudentName");
 71  
 72  //modelBuilder.Entity<Class>().ToTable("efdemo.ClassTable");
 73  //modelBuilder.Entity<Class>().Property(x => x.ClassID)
 74  //    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
 75  //    .IsRequired()
 76  //    .HasColumnName("TheClassID");
 77  
 78              modelBuilder.ComplexType<Address>();
 79              modelBuilder.Entity<Student>().Property(x=>x.Addre.StreetName).HasColumnName("StreetName").IsRequired();
 80              modelBuilder.Entity<Student>().Property(x => x.Addre.StreetNumber).HasColumnName("StreetNumber").IsRequired();
 81              modelBuilder.Entity<Student>().Property(x => x.DeliverAddre.StreetNumber).HasColumnName("DeliverStreeNumber");
 82              modelBuilder.Entity<Student>().Property(x => x.DeliverAddre.StreetName).HasColumnName("DeliverStreetName");
 83      
 84              modelBuilder.Entity<Student>().HasMany<Course>(x => x.Courses)
 85                  .WithMany(x => x.Students)          
 86                  .Map(m => 
 87                  {
 88                      m.ToTable("StudentCourse")
 89                          .MapLeftKey("StuID")
 90                          .MapRightKey("CorID");
 91                    
 92                  }
 93                  );
 94  
 95          }
 96      }
 97  
 98      [Table("efdemo.AnnoStudent",Schema="ef" )]
 99      public class Student
100      {
101          [Key]
102          public int StudentID { get; set; }
103          
104          [Required]
105          [MaxLength(120)]    
106          public string StudentName { get; set; }
107    
108          public Address Addre
109          {
110              get;
111              set;
112          }
113  
114          public Address DeliverAddre
115          {
116              get;
117              set;
118          }
119  
120          public virtual IList<Course> Courses { get; set; }
121  
122          public Student()
123          {
124              this.Courses = new List<Course>();
125          }
126      }
127  
128      [Table("efdemo.AnnoClass",Schema="ef")]
129      public class Class
130      {
131          [Key]
132          [Column("AnnoClassID")]      
133          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
134          public int ClassID { get; set; }
135          public string ClassName { get; set; }
136          public IList<Student> Students { get; set; }
137  
138          public Class()
139          {
140              this.Students = new List<Student>();
141          }
142      }
143  
144     
145      public class Address
146      {
147        
148          public int StreetNumber
149          {
150              get;
151              set;
152          }
153  
154       
155          [StringLength(125,MinimumLength=1)]
156          public string StreetName
157          {
158              get;
159              set;
160          }
161      }
162  
163      public class Course
164      {
165          [Key]
166          [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
167          public int CourseID
168          {
169              get;
170              set;
171          }
172  
173          [StringLength(125,MinimumLength=1)]  
174          public string CourseName { get; set; }
175  
176          public virtual IList<Student> Students { get; set; }
177  
178          public Course()
179          {
180              this.Students = new List<Student>();
181          }
182      }
183  
184  }
上面代码中分别演示了两种方法:

一种使用Annotation。

1 [Table("efdemo.AnnoStudent",Schema="ef" )]   
2 public class Student     {...}
另一种是基于方法的:
1 modelBuilder.ComplexType<Address>();       
2  
3 modelBuilder.Entity<Student>().Property(x=>x.Addre.StreetName).HasColumnName("StreetName").IsRequired();
未完待续。。。。

转载于:https://www.cnblogs.com/tonykan/archive/2012/11/22/2781857.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值