类型或命名空间名称"Key"无法找到。

8
「Key」属性对于实体框架对我不起作用。 我有一个「控制台」应用程序,并尝试添加该类:
public class Post
{
    [Key]
    public int IDPost { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int IDBlog { get; set; }
    public virtual Blog Blog { get; set; }
}

我遇到了这些错误:

找不到类型或命名空间名称“Key”(您是否缺少 using 指令或程序集引用?)

找不到类型或命名空间名称“KeyAttribute”(您是否缺少 using 指令或程序集引用?)

我已添加了以下 using:
using System.Data.Entity;

我已将以下引用添加到项目中:

EntityFramework
EntityFramework.SqlServer
System.ComponentModel.DataAnnotations

我正在使用EF6和VS2012。

我缺少哪个引用?


2
把光标放在 Key 上,按下 Ctrl + 句点。如果出现菜单,请选择添加 using 语句的选项。 - gunr2171
1
啊哈,太棒了。非常感谢。我需要“using System.ComponentModel.DataAnnotations;”。 - Guerrilla
4个回答

15

在EF6中,System.Data.Entity已被替换为System.Data.Entity.Core。请确保您不再引用任何EF5的dll,并使用以下内容替换您的using导入:

System.Data.Entity.Core

此外,[Key] 来自于

System.ComponentModel.DataAnnotations

命名空间。如果您在类的 using 语句中包含了它,它应该会编译。


1

对于我自己,我使用了小写的 [key] 而不是大写的 [Key],因此在遇到这个问题时,请务必检查一下。


0

我遇到了同样的错误,因为项目没有保存。


0

我在使用Visual Studio 2010创建asp.net Webforms应用程序时遇到了同样的错误。我按照以下步骤操作后,问题得到了解决。

  1. 打开NuGet包管理器并搜索System.data.entity。
  2. 安装它。
  3. 添加using System.ComponentModel.DataAnnotations;的引用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接