EntityFramework 有几种方式可实现数据库表与实体的关系配置(relationship)
- convention -
- annotation -
- fluent api -
使用数据注解
实体类通常是在Models目录下,直接在实体类上添加属性注解,比如[Required]/[Key]等.
1using System.ComponentModel.DataAnnotations; 2 3public class User() 4{ 5 [Key] 6 public string UserId { get; set; } 7 8 [Required] 9 public string UserName { get; set; } 10}
重写配置方法
在自己实现的XxxDbContext数据库上下文类中重写配置方法,用Fluent API的方式添加所有实体的配置.
1using Microsoft.EntityFrameworkCore; 2 3public partial class XxxDbContext : DbContext 4{ 5 public XxxDbContext() 6 { 7 } 8 9 public HaoyikuDbContext(DbContextOptions<HaoyikuDbContext> options) 10 : base(options) 11 { 12 } 13 14 public DbSet<User> Users { get; set; } 15 16 // 重写以下方法 17 protected override void OnModelCreating(ModelBuilder modelBuilder) 18 { 19 // 添加实体的配置 20 modelBuilder.Entity<BizOrderPush>().HasKey(); 21 } 22}
实现实体类配置接口
-
新建
ModelConfigurations目录,在该目录下新增每一个实体对应的配置类.using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders;
/// <summary> /// 用户实体-模型配置 /// </summary> public class UserConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasKey(o => o.UserId); builder.Property(o => o.UserName).IsRequired(); } }
单独配置每一个实体类后,通过以下方法设置
1using Microsoft.EntityFrameworkCore; 2 3public partial class XxxDbContext : DbContext 4{ 5 public XxxDbContext() 6 { 7 } 8 9 public HaoyikuDbContext(DbContextOptions<HaoyikuDbContext> options) 10 : base(options) 11 { 12 } 13 14 public DbSet<User> Users { get; set; } 15 16 // 重写以下方法 17 protected override void OnModelCreating(ModelBuilder modelBuilder) 18 { 19 // 添加实体的配置 20 modelBuilder.ApplyConfiguration(new UserConfiguration()); 21 base.OnModelCreating(modelBuilder); 22 } 23}
以上几种方式可以共存,至于到底用哪种,推荐用哪种,各位看着办吧.
