对于使用实体框架映射复合主键,我们可以使用两种方法。
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/zh-cn/library/jj591617(v=vs.113 ) .aspx
2)如何使用EF 6 Fluent Api添加复合唯一键?
SomeId
astring
还是anint
?