如何从mysql efcore中的两个外键生成主键

fhity93d  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(359)

我有一些问题,使主键从两个外国键
模型示例:element、color、elementtocolor
elementtocolor应该包含两个表示元素和颜色关系的foregin键

[Key,Column(Order = 1)]
public Int ElementId {get; set;} 

[Key,Column(Order = 2)]
public Int ColorId {get; set;}

但当我尝试添加迁移时失败了
elementtocolor必须有主键
但为Map表之王设置主键是错误的,它会使数据变得复杂
1,1,1
2,1,1
...
那样的话我该怎么办
我使用:
应用程序:asp.net core 2.1 webapi
数据库:mysql
orm:mysql efcore

aemubtdh

aemubtdh1#

找到了,我需要使用fluent api:
在applicationdbcontext中,我应该重写modelCreating的方法,如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ElementToColor>().HasKey(e => new { e.ElementId, e.ColorId }
    );

相关问题