简体   繁体   English

EntityType在MVC 4中没有定义键

[英]EntityType has no key defined in MVC 4

I have started to learn MVC making the tutorial on ASP.net website but I cannot understand one thing. 我已经开始学习在ASP.net网站上制作MVC的教程,但我一无所知。

When I create the controller and the model it gives me an error 当我创建控制器和模型时,它给我一个错误

System.Data.Entity.Edm.EdmEntityType: : EntityType 'TusofonaFields' has no key defined. System.Data.Entity.Edm.EdmEntityType :: EntityType'TusofonaFields'没有定义键。 Define the key for this EntityType. 定义此EntityType的键。

I try to search on web, and they always says its missing the [Key] on Id, but unfortenatly my visual studio gives me an error: 我尝试在网络上搜索,但他们总是说它缺少Id上的[Key],但我的Visual Studio经常给我一个错误:

The type or namespace name 'Key' could not be found (are you missing a using directive or an assembly reference?) 找不到类型或名称空间名称“键”(您是否缺少using指令或程序集引用?)

My code: 我的代码:

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

And the model: 和模型:

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

} }

If you are using the MVC4 wizard to create the view and you do not want a key in the viewModel, make sure that the "Data context class" textbox is empty in the dialog. 如果您使用MVC4向导创建视图,并且不想在viewModel中使用键,请确保对话框中的“数据上下文类”文本框为空。 If this box is filled with an EntityFramework DB Context, you will get this error. 如果此框填充了EntityFramework数据库上下文,则会收到此错误。 Remove it, and the error goes away. 删除它,错误消失。

Well, the error tells you what's going on: you are the missing reference. 好吧,该错误告诉您正在发生的事情:您是缺少的参考。

In EntityFramework 4: Check that you have System.ComponentModel.DataAnnotations in project's references. 在EntityFramework 4中:检查项目的引用中是否有System.ComponentModel.DataAnnotations。 Then add using System.ComponentModel.DataAnnotations; 然后using System.ComponentModel.DataAnnotations;添加using System.ComponentModel.DataAnnotations; namespace at the top of the cs file or use mouse2 on [Key]>Resolve>using System.ComponentModel.DataAnnotations; cs文件顶部的名称空间,或在[Key]>Resolve>using System.ComponentModel.DataAnnotations;使用mouse2, [Key]>Resolve>using System.ComponentModel.DataAnnotations;

If you are using EntityFramework 5 the namespace you need is System.ComponentModel.DataAnnotations.Schema 如果您使用的是EntityFramework 5,则所需的命名空间为System.ComponentModel.DataAnnotations.Schema

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM