Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 338
DevT Avatar asked Apr 25 '13 06:04

DevT


3 Answers

Add namespace

using System.ComponentModel.DataAnnotations;

Add key attribute to your CustomerID like this

[Key]
public int CustomerID { get; set; }

then build the application and try to add controller. This will work

like image 180
Kiran.Bakwad Avatar answered Nov 15 '22 23:11

Kiran.Bakwad


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

like image 21
archil Avatar answered Nov 15 '22 23:11

archil


I had the same problem. I restarted the project 3 times before I found the solution that worked for me. I had a public class that I manually created called UserContext. When I ran the wizard to add an ADO class the wizard generated a partial class of UserContext. I deleted my usercontext class and I modified the class that VS generated for me.

namespace UserLayer.Models
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public class UserContext : DbContext
    {

        public DbSet<UserDetail> UserDetails { get; set; }
    }
}

Now it may have had worked without the modification. Perhaps deleting my version of the class would have work. I do not know. In retropect I encountered your error when I tried to add the controller. I suspect this is a bug in VS2012 because a partial class and a public class of the same name can exist. The intent is to allow the programmer to extend the definition of the partial class.

like image 40
Darfdm Avatar answered Nov 15 '22 21:11

Darfdm