2013-06-06 30 views
1

我已经开始学习在ASP.net网站上制作教程的MVC,但我无法理解一件事。EntityType没有在MVC中定义的键4

当我创建控制器,它给我一个错误

System.Data.Entity.Edm.EdmEntityType: : EntityType 'TusofonaFields' has no key defined. Define the key for this EntityType.

我尝试在网络搜索的模式,他们总是说,它缺少的ID [键],但unfortenatly我的Visual Studio提供了我一个错误:

The type or namespace name 'Key' could not be found (are you missing a using directive or an assembly reference?)

我的代码:

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

}

+0

阅读错误信息;它会告诉你这个问题:你缺少一个命名空间。在MSDN上查找'KeyAttribute',你会发现它在'System.ComponentModel.DataAnnotations'中。为此添加'使用';它会工作。错误消息尽量有帮助;读它们! – anaximander

+0

我错过了2件事,但最主要的是参考:using System.ComponentModel.DataAnnotations; (我试过[Key]属性,但因为我没有参考,它被处理为错误) – macieira

回答

1

好,误差会告诉你这是怎么回事:你是丢失的引用。

In EntityFramework 4: 检查在项目的引用中是否有System.ComponentModel.DataAnnotations。 然后在CS文件的顶部添加using System.ComponentModel.DataAnnotations;命名空间或[Key]>Resolve>using System.ComponentModel.DataAnnotations;

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

+0

谢谢。它缺少代码:使用System.ComponentModel.DataAnnotations ;.谢谢 – macieira

4

如果您使用的是MVC4向导来创建视图和你不要在viewModel中使用关键字,确保对话框中的“Data context class”文本框为空。如果此框填充了EntityFramework数据库上下文,则会出现此错误。删除它,错误消失。

+1

这是我的解决方案。 –

相关问题