EFCore中数据表的两种配置方式


1、Data Annotation
把配置以特性(Annotation)的形式标注在实体类中
[Table("T_Dogs")]
public class Dog
{
public int Id { get; set; }
[Required]
[MaxLength(22)]
public string Name { get; set; }
}
优点:简单
缺点:耦合

2、FluentAPI
builder.ToTable("T_Books");
把配置写到单独的配置类中
优点:解耦
缺点:复杂
public class Book
{
public long Id { get; set; } //主题
public string Title { get; set; } //标题
public DateTime PubTime { get; set; } //发布日期
}

class BookConfig : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.ToTable("T_Books");
builder.Property(b => b.Title).HasMaxLength(50).IsRequired();
}
}

3、大部分功能重叠。可以混用,但是不建议混用