实体框架4& Code First CTP 5 - 缺少钥匙

发布于 2024-10-16 11:49:22 字数 881 浏览 3 评论 0原文

有人能理解这个错误吗?

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

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

我定义了这个实体:

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 名称的类,该错误有何意义。

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

Can someone make sense of this error?

One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'Address' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: The EntitySet Addresses is based on type Address that has no keys defined.

I have this entity defined:

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

My question is: how does the error make any sense for a class that both has a Key attribute data annotation as well as the conventional ID name for its PK.

I would think this class satisfies all rules needed for a meaningful entity to be generated from it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东北女汉子 2024-10-23 11:49:22

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

public int ID { get; set; }

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

Like Craig mentioned, making ID a property will solve your problem.

public int ID { get; set; }

Besides, you don't need the [Key] attribute on ID, it will be recognized as object identifier (i.e. Primary Key) by code first based on conventions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文