MappingsTo Database
Model-wide Mapping
  • Set default Schema
  • Set Custom Convetions
Entity Mapping
  • To Single or Multiple Tables and Schema
  • To Complex type
  • Inheritance Hierarchies
Property Mapping
  • To Column, Column Name, Column Type, Nullable or Not Null Column, Column size, Columns Order
  • To Concurrency column
  • To Foreign key column
  • To configure relationships
复制代码
public class SchoolContext: DbContext 
{
    public SchoolDBContext(): base() 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure domain classes using modelBuilder here

        base.OnModelCreating(modelBuilder);
    }
}
复制代码

 

在OnModelCreating方法中配置Fluent API

Code First配置优先顺序为:Fluent API > DataAnnotations > default conventions

EntityTypeConfiguration

EntityTypeConfiguration是一个重要的类,

Method NameReturn TypeDescription
HasKey<TKey> EntityTypeConfiguration 为实体类配置主键
HasMany<TTargetEntity> ManyNavigationPropertyConfiguration 配置多对多的关系
HasOptional<TTargetEntity> OptionalNavigationPropertyConfiguration

配置从这个实体中可选的关系,这个实体的实例可以没有和关系就保存到数据库中,数据库中的外键可为nullable

HasRequired<TTargetEntity> RequiredNavigationPropertyConfiguration

配置从这个实体中必须的关系,实体的实例如果没有指定关系不能保存在数据库中,数据库外键为non-nullable

Ignore<TProperty> Void 排除实体的属性不映射到数据库中
Map EntityTypeConfiguration 允许与此实体类型映射到数据库架构的高级配置有关。
Property<T> StructuralTypeConfiguration 配置在该类型上定义的结构属性
ToTable Void 配置此实体类型映射到的表名。

 

 

Entity Mappings

 

复制代码
public class Student
{
    public Student()
    { 
        
    }
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public byte[]  Photo { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }
        
    public Standard Standard { get; set; }
}
    
public class Standard
{
    public Standard()
    { 
        
    }
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> Students { get; set; }
   
    }
复制代码

 

 

 

Configure Default Schema

 

复制代码
public class SchoolContext: DbContext 
{
    public SchoolDBContext(): base() 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure default schema
        modelBuilder.HasDefaultSchema("Admin");
    }
}
复制代码

 

 配置实体映射到表

复制代码
namespace CodeFirst_FluentAPI_Tutorials
{
        
    public class SchoolContext: DbContext 
    {
        public SchoolDBContext(): base() 
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
                //Configure default schema
            modelBuilder.HasDefaultSchema("Admin");
                    
            //Map entity to table
            modelBuilder.Entity<Student>().ToTable("StudentInfo");
            modelBuilder.Entity<Standard>().ToTable("StandardInfo","dbo");

        }
    }
}
复制代码

 

 

配置实体到多个表中

复制代码
namespace CodeFirst_FluentAPI_Tutorials
{
        
    public class SchoolContext: DbContext 
    {
        public SchoolDBContext(): base() 
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().Map(m =>
            {
                m.Properties(p => new { p.StudentId, p.StudentName});
                m.ToTable("StudentInfo");

            }).Map(m => {
                m.Properties(p => new { p.StudentId, p.Height, p.Weight, p.Photo, p.DateOfBirth});
                m.ToTable("StudentInfoDetail");

            });

            modelBuilder.Entity<Standard>().ToTable("StandardInfo");

        }
    }
}
复制代码

 

 

 

 

Property Mappings 

复制代码
public class SchoolContext: DbContext 
{
    public SchoolDBContext(): base() 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure primary key
        modelBuilder.Entity<Student>().HasKey<int>(s => s.StudentKey);
        modelBuilder.Entity<Standard>().HasKey<int>(s => s.StandardKey);

        //Configure composite primary key
        modelBuilder.Entity<Student>().HasKey<int>(s => new { s.StudentKey, s.StudentName }); 
    }
}
复制代码

 

 

 

复制代码
public class SchoolContext: DbContext 
{
    public SchoolDBContext(): base() 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure Column
        modelBuilder.Entity<Student>()
                    .Property(p => p.DateOfBirth)
                    .HasColumnName("DoB")
                    .HasColumnOrder(3)
                    .HasColumnType("datetime2");
    }
}
复制代码

 

 

 

 

配置nullable和non-nullable

复制代码
namespace CodeFirst_FluentAPI_Tutorials
{
        
    public class SchoolContext: DbContext 
    {
        public SchoolDBContext(): base() 
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
                //Configure Null Column
            modelBuilder.Entity<Student>()
                    .Property(p => p.Heigth)
                    .IsOptional();
                        
                //Configure NotNull Column
                modelBuilder.Entity<Student>()
                    .Property(p => p.Weight)
                    .IsRequired();
        }
    }
}
复制代码

 

配置列的长度

复制代码
namespace CodeFirst_FluentAPI_Tutorials
{
        
    public class SchoolContext: DbContext 
    {
        public SchoolDBContext(): base() 
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set StudentName column size to 50
            modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .HasMaxLength(50);
                        
            //Set StudentName column size to 50 and change datatype to nchar 
            //IsFixedLength() change datatype from nvarchar to nchar
            modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .HasMaxLength(50).IsFixedLength();
                        
            //Set size decimal(2,2)
                modelBuilder.Entity<Student>()
                    .Property(p => p.Height)
                    .HasPrecision(2, 2);
        }
    }
}
复制代码

 

配置并发列

复制代码
namespace CodeFirst_FluentAPI_Tutorials
{
        
    public class SchoolContext: DbContext 
    {
        public SchoolDBContext(): base() 
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set StudentName as concurrency column
            modelBuilder.Entity<Student>()
                    .Property(p => p.StudentName)
                    .IsConcurrencyToken();
        }
    }
}
复制代码

 

也可以用IsRowVersion()来配置byte[]数组