c# - EF Core Composite Key,一个外键,一个自增

标签 c# sql-server entity-framework entity-framework-core

我有这个实体:

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");
        });

所以两个问题:

  1. 如何在 OnModelCreating 方法中创建外键?
  2. 如何使 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 列,只使用 PlayerScoreIdScoreWhen 作为复合键....

但是,我仍然有一个问题是如何将 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/

相关文章:

sql - 如何编写 SSIS SQL 代理作业步骤脚本以在本地主机上运行?

sql - 将 sql 结果导出到 CSV 时如何在单个单元格中使用逗号分隔值

linq - Entity Framework : Best way to query for a set of dates using Linq

c# - 如何删除 dbo.AspNetUserClaims 和 dbo.AspNetUserLogins 表(IdentityUserClaim 和 IdentityUserLogin 实体)?

sql-server - 没有 CASE 语句的存储过程

c# - 使用 HttpClient,在 301 的情况下如何防止自动重定向并获取原始状态代码和转发 Url

c# - 如何在多语言 Web 应用程序中转换和存储可配置项?

c# - 内联参数化查询超时

c# - C# 使用表达式树生成分组后带有求和的 select 语句

C# Invalidate 不调用 paint 方法