entity type has no key defined - Code first

2020-08-25 05:20发布

问题:

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

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

回答1:

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



回答2:

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.



回答3:

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



回答4:

there was an error running the selected code generator unable to retrieve metadata for entity type has no key defined.

  • one more important thing sql table only takes [Id] then entity framework will work if you use other primary key like[MenuId] it wont.
  • you should add validation on Model which is Key and Column order
  • column order = 1 because after [key] added its increment by 1 that's why

Model

[Key]
        [Column(Order = 1)]
        public int RoleIdName { get; set; }

then build this after create a controller under entity frame work it will work

i hope it helps.