【问题标题】:EntityType has no key defined in MVC 4EntityType 没有在 MVC 4 中定义的键
【发布时间】:2013-06-06 09:54:32
【问题描述】:

我已经开始在 ASP.net 网站上学习 MVC 制作教程但我不懂一件事。

当我创建控制器和模型时,它给了我一个错误

System.Data.Entity.Edm.EdmEntityType: : EntityType 'TusofonaFields' 没有定义键。定义此 EntityType 的键。

我尝试在网络上搜索,他们总是说它缺少 Id 上的 [Key],但不幸的是我的视觉工作室给了我一个错误:

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

我的代码:

public ActionResult Index()
{
    return View(db.site_membros.ToList());
}

还有模特:

namespace MvcApplication2
{
    public class TusofonaFields
    {
      public int IDMembro { get; set; }
      public string Alcunha { get; set; }        
      public DateTime Aniversario { get; set; }        
      public string Foto { get; set; }
    }

public class TusofonaTable : DbContext
{        
    public DbSet<TusofonaFields> site_membros { get; set; }
}   

}

【问题讨论】:

  • 阅读错误信息;它告诉你问题:你缺少一个命名空间。在 MSDN 上查找 KeyAttribute,您会发现它在 System.ComponentModel.DataAnnotations 中。为此添加using;它会工作的。错误消息试图提供帮助;阅读它们!
  • 我遗漏了两件事,但主要的是参考:使用 System.ComponentModel.DataAnnotations; (我尝试了 [Key] 属性,但由于我没有引用,因此将其作为错误处理)

标签: c# asp.net-mvc entity-framework asp.net-mvc-4


【解决方案1】:

如果您正在使用 MVC4 向导创建视图并且您不希望在 viewModel 中有键,请确保对话框中的“数据上下文类”文本框为空。如果此框填充了 EntityFramework DB 上下文,您将收到此错误。删除它,错误就会消失。

【讨论】:

  • 这是我的解决方案。
【解决方案2】:

嗯,错误告诉你发生了什么:你是缺少的参考。

在 EntityFramework 4 中: 检查项目引用中是否有 System.ComponentModel.DataAnnotations。 然后在cs文件顶部添加using System.ComponentModel.DataAnnotations;命名空间或者在[Key]&gt;Resolve&gt;using System.ComponentModel.DataAnnotations;上使用mouse2

如果您使用的是 EntityFramework 5,您需要的命名空间是 System.ComponentModel.DataAnnotations.Schema

【讨论】:

  • 谢谢。它缺少代码:使用 System.ComponentModel.DataAnnotations;。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 2016-03-16
  • 2013-08-04
  • 2012-12-10
相关资源
最近更新 更多