【问题标题】:Entity Framework 4 & Code First CTP 5 - Missing Key实体框架 4 和代码优先 CTP 5 - 缺少密钥
【发布时间】:2011-02-08 19:54:59
【问题描述】:

有人能理解这个错误吗?

在模型生成过程中检测到一个或多个验证错误:

System.Data.Edm.EdmEntityType: : EntityType 'Address' 没有定义键。定义此 EntityType 的键。 System.Data.Edm.EdmEntitySet:EntityType:EntitySet 地址基于未定义键的类型地址。

我已经定义了这个实体:

public class Address
{
    [Key]
    public int ID;

    [Required]
    [MinLength(1)]
    [MaxLength(200)]
    public string Address1 { get; set; }

    [MinLength(1)]
    [MaxLength(200)]
    public string Address2 { get; set; }

    [Required]
    [MinLength(1)]
    [MaxLength(10)]
    public string Zip { get; set; }

    [MinLength(1)]
    [MaxLength(100)]
    public string Province { get; set; }

    public virtual US_State State { get; set; }

    [Required]
    public virtual Country Country { get; set; }
}

我的问题是:对于既具有 Key 属性数据注释以及其 PK 的常规 ID 名称的类,该错误有什么意义。

我认为这个类满足从它生成有意义的实体所需的所有规则。

【问题讨论】:

  • 为什么你的ID 是一个字段而不是一个属性?
  • @Caig:因为我错过了 ;-)

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


【解决方案1】:

就像 Craig 提到的,将 ID 设为属性将解决您的问题。

public int ID { get; set; }

此外,您不需要ID 上的[Key] 属性,它将根据约定被代码优先识别为对象标识符(即主键)。

【讨论】:

    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    相关资源
    最近更新 更多