在上一节中我们讲解了一个简单的entity framework application。在这一节里我们将使用Data annotation 和 Fluent API 进行 实体模型的配置。这里我们主要讲解的是通过Fluent API 来进行配置,因为相对于Data Annotation 我更喜欢这种干净的代码而且实体代码是自动生成的使用Fluent API的方式更加灵活和方便。
1. Length ——主要描述数据的长度
Data Annotation
MinLength(nn)
MaxLength(nn)
StringLength(nn)
FluentAPI
Entity<T>.Property(t=>t.PropertyName).HasMaxLength(nn)
继续上一节中示例,对于SchoolName 或 StudentName 之内的字段我们要对它的长度进行约定此时我们就可以通过配置来完成。
采用Data Annotation 的方式,在之后的例子中我将不再采用此种方式。
DataAnnotation
[MaxLength(100)] public string SchoolName { get; set; }
现在我们来讲解我们的重点 Fluent API
新建一类文件继承EntityTypeConfiguration<Ttype> 泛型类
StudentConfiguration
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel.DataAnnotations; 4 using System.Data.Entity.ModelConfiguration; 5 using System.Linq; 6 using System.Text; 7 8 namespace Stephen.Sample.AEF.CodeFirstSample.Domain.DBConfiguration 9 { 10 public class StudentConfiguration:EntityTypeConfiguration<Student> 11 { 12 public StudentConfiguration() 13 { 14 Property(n => n.StudentName).HasMaxLength(10); 15 Property(n => n.StudentName).HasColumnType("varchar"); 16 Property(n => n.StudentName).IsRequired(); 17 } 18 } 19 }
在Context类中重写OnModelCreateing 方法将StudentConfiguration 类注册。
OnModelCreating
1 public class SchoolDbContext : DbContext 2 { 3 public DbSet<School> Schools { get; set; } 4 public DbSet<Classroom> Classrooms { get; set; } 5 public DbSet<Student> Students { get; set; } 6 7 protected override void OnModelCreating(DbModelBuilder modelBuilder) 8 { 9 modelBuilder.Configurations.Add(new StudentConfiguration()); 10 modelBuilder.Configurations.Add(new AddressConfiguration()); 11 } 12 }
现在我们将之前的测试代码中student的name的长度改的稍微长一点,再来看一下: