macieira
macieira

Reputation: 359

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.

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

}

Upvotes: 1

Views: 16987

Answers (2)

Jerry Finegan
Jerry Finegan

Reputation: 49

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.

Upvotes: 4

Tomi Lammi
Tomi Lammi

Reputation: 2126

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

Upvotes: 1

Related Questions