要更改EF中的默认配置有两个方法,一个是用Data Annotations(在命名空间System.ComponentModel.DataAnnotations;),直接作用于类的属性上面;还有一个就是Fluent API,通过新增相应的配置类来覆盖默认配置。现在我们用这两个来对比了解EF中的约定配置。
主键:KEY
Data Annotations:通过Key关键字来标识一个主键
[Key] public int DestinationId { get; set; }
Fluent API:
public class BreakAwayContext : DbContext { public DbSet<Destination> Destinations { get; set; } public DbSet<Lodging> Lodgings { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //Fluent API modelBuilder.Entity<Destination>().HasKey(d => d.DestinationId); base.OnModelCreating(modelBuilder); } }
外键
Data Annotations:
public int DestinationId { get; set; } [ForeignKey("DestinationId")] public Destination Destination { get; set; }
注意,指定列名存在,如上面的DestinationId,则类中必须存在名称为DestinationId的属性。
Fluent API:
modelBuilder.Entity<Lodging>().HasRequired(p => p.Destination).WithMany(p=>p.Lodgings).HasFo