实体类型具有多个具有 [Key] 属性的属性。复合主键只能使用“OnModelCreating”中的“HasKey”设置。

Ste*_*eve 9 c# entity-framework-core

我有这个表,它有 2 列来形成组合键。我正在使用 EF Core。这是我的模型

public class MyModel
{
    [Key]
    [Column(Order = 0)]
    [StringLength(255)]
    public string column1 { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(255)]
    public string column2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我运行 xunit 测试时,出现此错误

The entity type xxx has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKey' in 'OnModelCreating'.'
Run Code Online (Sandbox Code Playgroud)

这是 xunit 的代码。

    public MyServicesTest()
    {
        var options = new DbContextOptionsBuilder<MyContext>();
        options.UseSqlServer(myServiceSqlConnStr);

        _myServicesContext = new MyContext(options.Options);

        _myServicesContext.Database.EnsureDeleted();

    }
Run Code Online (Sandbox Code Playgroud)

错误来自_myServicesContext.Database.EnsureDeleted();

这是我的上下文类

public class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyContext).Assembly);
        
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用OnModelCreatingMyContext仍然出现同样的错误。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {            
        modelBuilder.Entity<MyModel>()
              .HasKey(m => new { m.column1 , m.column2 });
    }
Run Code Online (Sandbox Code Playgroud)

Pau*_*ram 10

看看EF 键

强调我的:

您还可以将多个属性配置为实体的键 - 这称为复合键。复合键只能使用 Fluent API 进行配置;约定永远不会设置复合键,并且您不能使用数据注释来配置复合键。

您必须[Key]从类中删除属性,并且仅在下面指定它们OnModelCreating

protected override void OnModelCreating(ModelBuilder modelBuilder)
{            
    modelBuilder.Entity<MyModel>()
          .HasKey(m => new { m.column1 , m.column2 });
}
Run Code Online (Sandbox Code Playgroud)

请注意EF6,在 EF Core 之前,您可以使用带有数据注释的组合键。


小智 7

在 EF7 中,您可以在模型类上使用 [PrimaryKey] 属性。

[PrimaryKey(nameof(column1), nameof(column2))]
public class MyModel
{
    [Column(Order = 0)]
    [StringLength(255)]
    public string column1 { get; set; }

    [Column(Order = 1)]
    [StringLength(255)]
    public string column2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)