【问题标题】:EF not recognizing Column attribute for code first?EF 不首先识别代码的列属性?
【发布时间】:2019-08-01 22:42:12
【问题描述】:

我对 Code First 实体有以下类定义:

public class Matches
{
    [Key]
    [Required]
    [Column(Order = 1)]
    public Guid MatchGroup { get; set; }

    [Key]
    [Required]
    [Column(Order = 2)]
    public long ProcedureId { get; set; }

    public long MatchLevelId { get; set; }

    [ForeignKey("ProcedureId")]
    public virtual Procedure Procedure { get; set; }

    [ForeignKey("MatchLevelId")]
    public virtual ProcedureMatchLevel MatchLevel { get; set; }
}

但是,在创建初始迁移时,我收到以下错误:

Unable to determine composite primary key ordering for type 
'Entities.Procedures' Use the ColumnAttribute or the HasKey 
method to specify an order for composite primary keys.

如您所见,我使用的是[Column] 属性。

以前有人遇到过这个问题吗?我尝试使用[Key, ForeignKey("Procedure")] 切换我的[ForeignKey] 声明所在的属性,但出现相同的错误。


程序类:

[Table("ProcedureList")]
public class Procedure
{
    [Required]
    public int ProcedureId { get; set; }
    [Required]
    public string Code { get; set; }
    [Required]
    public string Description { get; set; }
}

【问题讨论】:

  • 你的 DbContext 类和你的 Procedure 类是什么样的?我认为问题可能出在 Procedure 类而不是 Matches 类。
  • 如果我使用 Fluent API(modelBuilder.Entity<Matches>().HasKey(x => new { x.MatchGroup, x.ProcedureId });,但我没有将 Fluent API 用于其他任何事情,所以我想知道我在使用数据属性时做错了什么保持一定的一致性。
  • 列序索引从0开始,你确定你的订单是1&2而不是0&1
  • this related or duplicated 我看到订单是从零开始的索引。
  • @PhillipCopley 看看程序类,为什么你没有主键?

标签: c# entity-framework ef-code-first


【解决方案1】:

你还需要定义Procedure类的主键

[Table("ProcedureList")]
public class Procedure
{
    [Key]
    [Required]
    public int ProcedureId { get; set; }
    [Required]
    public string Code { get; set; }
    [Required]
    public string Description { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    相关资源
    最近更新 更多