In the previous section, we explained a simple entity framework application. In this section, we will use the Data annotation and Fluent APIs to configure the object model. Here we mainly explain how to configure through Fluent API, compared with Data Annotation, I prefer this kind of clean code and the entity code is automatically generated using Fluent API, which is more flexible and convenient.
1. Length -- mainly describes the Data Length
Data Annotation
MinLength (nn)
MaxLength (nn)
StringLength (nn)
FluentAPI
Entity <T>. Property (t => t. PropertyName). HasMaxLength (nn)
For the example in the previous section, we need to specify the length of the field in SchoolName or StudentName. In this case, we can configure it.
The Data Annotation method will not be used in subsequent examples.
DataAnnotation
[MaxLength(100)] public string SchoolName { get; set; }
Now let's explain our key Fluent API
Create a new type of file that inherits EntityTypeConfiguration <Ttype> generic class
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 }
Override the OnModelCreateing method in the Context class to register the StudentConfiguration class.
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 }
Now let's change the length of student's name in the previous test code to a little longer. Let's take a look at it again: