Search code examples
asp.net-mvcentity-framework-4

entity type has no key defined - Code first


I'm new to MVC as well as the entity framework. I searched lot and find few similar questions (e.g. Entity Type Has No Key Defined) but they don't solve my problem.

namespace MvcAppInvoice.Models
{
    public class Customer
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string SurName { get; set; }
        public virtual CustomerType Type { get; set; }
    }

    public class CustomerType
    {
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public virtual ICollection<Customer> customers { get; set; }
    }
}

Add Controller

When I try to add the controller it gives the following error:

Error


Solution

  • Typically, code first by convention implicitely sets key for entity type if property is named Id or TypeName+Id. In your case, TypeId is neither of them, so you should explicitely mark it as key, using KeyAttribute or with fluent syntax, using EntityTypeConfiguration.HasKey Method