我有这个实体:
public class PlayerScoreHistory
{
public int Id { get; set; }
public int PlayerScoreId { get; set; }
public DateTime ScoreWhen { get; set; }
}
我需要从这两个 Id
字段中创建一个复合键。 PlayerScoreId
需要是 PlayerScore.Id
的外键。 Id
需要是一个自动递增的 id。
所以,我得到了:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<PlayerScoreHistory>()
.HasKey(x => new { x.Id, x.PlayerScoreId });
}
这给了我复合键。我做了 Add-Migration Initial
给我初始迁移。
要获取外键,我只需在 constraints
参数中添加以下行:
migrationBuilder.CreateTable(
name: "PlayerScoreHistories",
columns: table => new
{
Id = table.Column<int>(nullable: false),
PlayerScoreId = table.Column<int>(nullable: false),
ScoreWhen = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PlayerScoreHistories", x => new { x.Id, x.PlayerScoreId });
table.ForeignKey("FK_PlayerScoreId", arg => new { arg.PlayerScoreId}, "PlayerScores", "Id");
});
所以两个问题:
- 如何在
OnModelCreating
方法中创建外键? - 如何使
Id
列成为数据库生成的字段并确保 EF Core 不会尝试设置值?
我不确定我可以选择哪些选项,因为 EF Core 非常新......
我得到的两个错误:
1.
当我将这一行添加到Id
column
参数配置时:
Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
我明白了
SQL Cannot insert explicit value for identity column in table 'Table' when IDENTITY_INSERT is set to OFF [duplicate]
2.
当我删除该行然后尝试添加一个实体时,我得到:
Can't insert null into column
Id
显然我介于两者之间......
到目前为止的编辑
我决定删除 Id
列,只使用 PlayerScoreId
和 ScoreWhen
作为复合键....
但是,我仍然有一个问题是如何将 OnModelCreating
标识 PlayerScoreId
作为外键 - 没有导航属性......
最佳答案
But, one question I still have is how to make OnModelCreating identity PlayerScoreId as a foreign key - without having navigation properties.....
您可以使用 HasOne
/WithMany
(或 HasMany
/WithOne
)方法而不指定导航属性,像往常一样结合 HasForeignKey
:
modelBuilder.Entity<PlayerScoreHistory>()
.HasOne<PlayerScore>()
.WithMany()
.HasForeignKey(e => e.PlayerScoreId);
关于c# - EF Core Composite Key,一个外键,一个自增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38946195/