Entity Framework(四):使用DbModelBuilder API创建表结构

DbContext类有一个OnModelCreating方法,它用于流利地配置领域类到数据库模式的映射。下面我们以fluent API的方式来定义映射。
首先,先将Product类注释掉,重新编写该类,重新编写后的Product类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace EFFluentAPI.Model
 8 {
 9     public class Product
10     {
11         public int ProductNo { get; set; }
12 
13         public string ProductName { get; set; }
14 
15         public double ProductPrice { get; set; }
16     }
17 }

然后在数据库上下文Context类中的OnModelCreating方法中使用fluent API来定义Product表的数据库模式:

 1 using EFFluentAPI.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data.Entity;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace EFFluentAPI.EFContext
10 {
11     public class Context:DbContext
12     {
13         public Context()
14             : base("DbConnection")
15         { }
16 
17         public DbSet<Product> Products { get; set; }
18 
19         /// <summary>
20         /// 重新OnModelCreating方法
21         /// </summary>
22         /// <param name="modelBuilder"></param>
23         protected override void OnModelCreating(DbModelBuilder modelBuilder)
24         {
25             //映射到表Product,ProductNo和ProductName作为复合主键
26             modelBuilder.Entity<Product>().ToTable("Product").HasKey(p=>new {p.ProductNo,p.ProductName});
27             //ProductNo映射到数据表中的列名是Id
28             modelBuilder.Entity<Product>().Property(p => p.ProductNo).HasColumnName("Id");
29             modelBuilder.Entity<Product>().Property(p => p.ProductName)
30                 .IsRequired() //设置ProductName是必须的,即不能为null,默认是可以为null的
31                 .IsUnicode()  //设置ProductName列为Unicode字符,实际上默认就是Unicode字符,所以该方法可以不写。
32                 .HasMaxLength(10); //设置ProductName列的最大长度是10
33             base.OnModelCreating(modelBuilder);
34         }
35     }
36 }

modelBuilder.Entity<Product>()会得到EntityTypeConfiguration类的一个实例。此外,使用fluent API的一个重要决定因素是我们是否使用了外部的POCO类,即实体模型类是否来自一个类库。我们无法修改类库中类的定义,所以不能通过数据注解来提供映射细节。这种情况下,我们必须使用fluent API。

什么是POCO?

POCO是指Plain Old Class Object,也就是最基本的CLR Class,在原先的EF中,实体类通常是从一个基类继承下来的,而且带有大量的属性描述。而POCO则是指最原始的Class,换句话说这个实体的Class仅仅需要从Object继承即可,不需要从某一个特定的基类继承。主要是配合Code First使用。Code First则是指我们先定义POCO这样的实体Class,然后生成数据库。实际上现在也可以使用Entity Framweork Power tools将已经存在的数据库反向生成POCO的Class(不通过edmx文件)。

程序运行后创建的数据库如下图所示:

 

posted @ 2017-08-23 15:46  .NET开发菜鸟  阅读(1008)  评论(0编辑  收藏  举报