前一篇博客介绍了EFCore
中的DB First
开发模式,该模式可以根据数据库生成实体类和数据库上下文,因此适用于数据库已经存在的场景。而与之相对应的,Code First
主要是根据自定义的实体类和数据库上下文反向构建数据库,因此也可以看做是DB First
的逆过程,下面开始介绍。
新建一个Web API
项目,使用NuGet
引入如下组件:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
新建实体类Author
、数据库上下文DaoDbContext
,如下图所示:
DaoDbContext
的代码如下所示:
using App.Models;
using Microsoft.EntityFrameworkCore;namespace App.Context
{public class DaoDbContext : DbContext{public DaoDbContext(){}public DaoDbContext(DbContextOptions options) : base(options){}protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlServer("Data Source=DSF-PC;Initial Catalog=Dao;User ID=sa;Password=123456;");}protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.Entity();base.OnModelCreating(modelBuilder);}public virtual DbSet Author { get; set; }}
}
Author
先不用添加代码:
namespace App.Models
{public class Author{}
}
Code First
模式通过实体类生成数据表,而数据表必然含有一个主键,在Code First
中可以使用[Key]
来标识实体类中的主键字段,代码如下:
using System.ComponentModel.DataAnnotations;namespace App.Models
{public class Author{/// /// 主键/// [Key]public int Id { get; set; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m1
然后更新数据库:
Update-Database
打开数据库查看新生成的Author
数据表,可以看到主键字段Id
已经生成,如下图所示:
在数据库中,部分字段的类型可能是varchar
或nvarchar
,此时可以通过[StringLength]
、[MinLength]
、[MaxLength]
对其长度进行标识。在Author
中新增Name
和Address
字段,代码如下:
using System.ComponentModel.DataAnnotations;namespace App.Models
{public class Author{/// /// 主键/// [Key]public int Id { get; set; }/// /// 姓名/// [MinLength(2)][MaxLength(20)]public string Name { get; set; }/// /// 地址/// [StringLength(40)]public string Address { get; set; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m2
然后更新数据库:
Update-Database
打开数据库查看新生成的Author
数据表,可以看到Name
和Address
字段已经生成,其中Name
字段最大长度为20
,Address
字段最大长度为40
,如下图所示:
在数据表中,主键不能为NULL
。如果希望其他字段也不能为NULL
,则可以使用[Required]
进行标识,下面对Author
进行修改,规定Name
字段不能为空,代码如下:
using System.ComponentModel.DataAnnotations;namespace App.Models
{public class Author{/// /// 主键/// [Key]public int Id { get; set; }/// /// 姓名/// [Required][MinLength(2)][MaxLength(20)]public string Name { get; set; }/// /// 地址/// [MinLength(5)][MaxLength(40)]public string Address { get; set; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m3
然后更新数据库:
Update-Database
打开数据库查看新生成的Author
数据表,可以看到Name
被定义为不能为NULL
,如下图所示:
在某些情况下,实体类中的部分字段并不需要在数据库中生成对应的字段,此时就可以使用[NotMapped]
进行标识。下面对Author
进行修改,添加一个Info
字段,代码如下:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace App.Models
{public class Author{/// /// 主键/// [Key]public int Id { get; set; }/// /// 姓名/// [Required][MinLength(2)][MaxLength(20)]public string Name { get; set; }/// /// 地址/// [MinLength(5)][MaxLength(40)]public string Address { get; set; }/// /// 信息/// [NotMapped]public string Info { get => $"姓名:{Name},地址:{Address}"; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m4
然后更新数据库:
Update-Database
打开数据库查看新生成的Author
数据表,可以看到实体类中的Info
字段并没有创建对应的字段,如下图所示:
在某些情况下,我们希望手动设置某个字段在数据表中对应的列名,此时就可以使用[Column]
进行标识,下面对Author
进行修改,给每个字段加上前缀Author_
,代码如下:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace App.Models
{public class Author{/// /// 主键/// [Key]public int Id { get; set; }/// /// 姓名/// [Required][MinLength(2)][MaxLength(20)][Column("Author_Name")]public string Name { get; set; }/// /// 地址/// [MinLength(5)][MaxLength(40)][Column("Author_Address")]public string Address { get; set; }/// /// 信息/// [NotMapped]public string Info { get => $"姓名:{Name},地址:{Address}"; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m5
然后更新数据库:
Update-Database
打开数据库查看新生成的Author
数据表,可以看到数据表中的字段已经加上了Author_
前缀,如下图所示:
如果希望手动设置数据表名称,则可以使用[Table]
进行标识,下面对Author
进行修改,将表名设置为T_AuthorInfo
,代码如下:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace App.Models
{[Table("T_AuthorInfo")]public class Author{/// /// 主键/// [Key]public int Id { get; set; }/// /// 姓名/// [Required][MinLength(2)][MaxLength(20)][Column("Author_Name")]public string Name { get; set; }/// /// 地址/// [MinLength(5)][MaxLength(40)][Column("Author_Address")]public string Address { get; set; }/// /// 信息/// [NotMapped]public string Info { get => $"姓名:{Name},地址:{Address}"; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m6
然后更新数据库:
Update-Database
打开数据库查看新生成的Author
数据表,可以看到数据表的名称已经修改为T_AuthorInfo
,如下图所示:
如果存在一对多的情况,则可以使用[ForeignKey]
对外键进行标识。新建一个实体类Book
,该类包含一个外键AuthorId
,代码如下:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace App.Models
{public class Book{/// /// 主键/// [Key]public int Id { get; set; }/// /// 书名/// [StringLength(30)]public string BookName { get; set; }/// /// 外键/// public int? AuthorId { get; set; }/// /// 导航属性/// [ForeignKey("AuthorId")]public virtual Author Author { get; set; }}
}
由于Author
与Book
是一对多的关系,因此Author
中需要定义一个Book
集合,代码如下:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;namespace App.Models
{public class Author{public Author(){Book = new HashSet();}/// /// 主键/// [Key]public int Id { get; set; }/// /// 姓名/// [Required][MinLength(2)][MaxLength(20)]public string Name { get; set; }/// /// 地址/// [MinLength(5)][MaxLength(40)]public string Address { get; set; }/// /// 信息/// [NotMapped]public string Info { get => $"姓名:{Name},地址:{Address}"; }/// /// 导航属性/// public virtual ICollection Book { get; set; }}
}
最后更新一下DaoDbContext
,代码如下:
using App.Models;
using Microsoft.EntityFrameworkCore;namespace App.Context
{public class DaoDbContext : DbContext{public DaoDbContext(){}public DaoDbContext(DbContextOptions options) : base(options){}protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlServer("Data Source=10.8.59.253;Initial Catalog=Dao;uid=sa;pwd=gis1a6b7c!Z;");}protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.Entity();modelBuilder.Entity();base.OnModelCreating(modelBuilder);}public virtual DbSet Author { get; set; }public virtual DbSet Book { get; set; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration m7
然后更新数据库:
Update-Database
打开数据库,可以看到数据表Book
已经生成,同时外键AuthorId
也已经成功创建,如下图所示:
到此为止,我们已经熟悉了基本的Code First
操作。其实Data Annotations
中还包含很多其他的属性标识,如[Range]
、[Comment]
、[RegularExpression]
等,有兴趣的同志可自行深入研究。
上面介绍了基于Data Annotations
的Code First
,该模式主要是通过给实体类打标签定义数据表。在EF Core
中,还有一种使用Fluent API
定义数据表的方法,下面开始介绍其使用方法,项目结构如下图所示:
定义Author
和Book
,代码如下:
using System.Collections.Generic;namespace App.Model
{public class Author{public Author(){Book = new HashSet();}/// /// 主键/// public int Id { get; set; }/// /// 姓名/// public string Name { get; set; }/// /// 地址/// public string Address { get; set; }/// /// 导航属性/// public virtual ICollection Book { get; set; }}
}
namespace App.Model
{public class Book{/// /// 主键/// public int Id { get; set; }/// /// 书名/// public string BookName { get; set; }/// /// 外键/// public int? AuthorId { get; set; }/// /// 导航属性/// public virtual Author Author { get; set; }}
}
AuthorConfiguration
和BookConfiguration
需要继承IEntityTypeConfiguration<>
接口,代码如下:
using App.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;namespace App.Config
{public class AuthorConfiguration : IEntityTypeConfiguration{public void Configure(EntityTypeBuilder builder){// 定义主键builder.ToTable("Author").HasKey(p => p.Id);// 定义字段Namebuilder.Property(p => p.Name).IsRequired().HasMaxLength(20);// 定义字段Addressbuilder.Property(p => p.Address).HasMaxLength(40);}}
}
using App.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;namespace App.Config
{public class BookConfiguration : IEntityTypeConfiguration{public void Configure(EntityTypeBuilder builder){// 定义主键builder.ToTable("Book").HasKey(p => p.Id);// 定义字段BookNamebuilder.Property(p => p.BookName).IsRequired().HasMaxLength(20);// 定义外键AuthorIdbuilder.HasOne(p => p.Author).WithMany(p => p.Book).HasForeignKey(p => p.AuthorId).OnDelete(DeleteBehavior.Cascade).HasConstraintName("FK_Book_Author");}}
}
最后添加DaoDbContext
部分,代码如下:
using App.Config;
using App.Model;
using Microsoft.EntityFrameworkCore;namespace App.Context
{public class DaoDbContext : DbContext{public DaoDbContext(){}public DaoDbContext(DbContextOptions options) : base(options){}protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlServer("Data Source=DSF-PC;Initial Catalog=Dao;User ID=sa;Password=123456;");}protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.ApplyConfiguration(new AuthorConfiguration());modelBuilder.ApplyConfiguration(new BookConfiguration());base.OnModelCreating(modelBuilder);}public virtual DbSet Author { get; set; }public virtual DbSet Book { get; set; }}
}
在NuGet
控制台中输入如下命令:
Add-Migration mig
然后更新数据库:
Update-Database
打开数据库,可以看到数据表Author
和Book
已经生成,同时外键AuthorId
也已经成功创建,如下图所示:
本文主要介绍了EF Core
中的Code First
模式,在实际开发过程中更推荐使用Fluent API
的方式,因为该方法耦合性较低且更加灵活。