EntityType has no key defined in MVC 4

asp.net-mvc asp.net-mvc-4 c# entity-framework

Question

I have started to learn MVC making the tutorial on ASP.net website but I cannot understand one thing.

When I create the controller and the model it gives me an error

System.Data.Entity.Edm.EdmEntityType: : EntityType 'TusofonaFields' has no key defined. Define the key for this 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:

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

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

}

1
1
1/18/2016 7:24:56 PM

Accepted Answer

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. Then add using System.ComponentModel.DataAnnotations; namespace at the top of the cs file or use mouse2 on [Key]>Resolve>using System.ComponentModel.DataAnnotations;

If you are using EntityFramework 5 the namespace you need is System.ComponentModel.DataAnnotations.Schema

1
6/6/2013 10:12:50 AM

Popular Answer

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. If this box is filled with an EntityFramework DB Context, you will get this error. Remove it, and the error goes away.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow