对于使用实体框架映射复合主键,我们可以使用两种方法。
1)通过重写 OnModelCreating() 方法
例如:我有一个名为 VehicleFeature 的模型类,如下所示。
public class VehicleFeature
{
public int VehicleId { get; set; }
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
我的 DBContext 中的代码就像,
public class VegaDbContext : DbContext
{
public DbSet<Make> Makes{get;set;}
public DbSet<Feature> Features{get;set;}
public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)
{
}
// we override the OnModelCreating method here.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
}
}
2)通过数据注释。
public class VehicleFeature
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int VehicleId { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int FeatureId{get;set;}
public Vehicle Vehicle{get;set;}
public Feature Feature{get;set;}
}
请参阅以下链接以获取更多信息。
1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx
2)如何使用 EF 6 Fluent Api 添加复合唯一键?