[c#] EntityType has no key defined error

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcApplication1.Controllers
{
    public class studentsController : Controller
    {
        //
        // GET: /students/

        public ActionResult details()
        {
            int id = 16;
            studentContext std = new studentContext();
           student first = std.details.Single(m => m.RollNo == id);
            return View(first);
        }

    }
}

DbContext Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcApplication1.Models
{
    public class studentContext : DbContext
    {
        public DbSet<student> details { get; set; }
    }
}

Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcApplication1.Models
{
    [Table("studentdetails")]
    public class student
    {
        public int RollNo;
        public string Name;
        public string Stream;
        public string Div;
    }
}

Database table:

CREATE TABLE [dbo].[studentdetails](
    [RollNo] [int] NULL,
    [Name] [nvarchar](50) NULL,
    [Stream] [nvarchar](50) NULL,
    [Div] [nvarchar](50) NULL
)  

In global.asax.cs

Database.SetInitializer<MvcApplication1.Models.studentContext>(null);

The above code lists all the classes I am working on. Upon running my application am receiving the error:

"One or more validation errors were detected during model generation" along with "Entity type has no key defined".

This question is related to c# .net entity-framework

The answer is


The Model class should be changed to :

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    [Table("studentdetails")]
    public class student
    {
        [Key]
        public int RollNo { get; set; }

        public string Name { get; set; }

        public string Stream { get; set; }

        public string Div { get; set; }
    }
}

The object must contain a field which will be used as the Primary Key, if you have a field named Id then this will by default be the primary key of the object to which Entity Framework will link to.

Otherwise, you should add the [Key] attribute above that field you wanna use as the Primary Key, and you'll also need to add the namespace System.ComponentModel.DataAnnotations:

public class myClass
{
    public int Id { get; set; }
    [Key]
    public string Name { get; set; }
}

https://stackoverflow.com/a/51180941/7003760


  1. Make sure public members of student class are defined as properties w/ {get; set;} (yours are public variables - a common mistake).

  2. Place a [Key] annotation on top of your chosen property.


There are several reasons this can happen. Some of these I found here, others I discovered on my own.

  • If the property is named something other than Id, you need to add the [Key] attribute to it.
  • The key needs to be a property, not a field.
  • The key needs to be public
  • The key needs to be a CLS-compliant type, meaning unsigned types like uint, ulong etc. are not allowed.
  • This error can also be caused by configuration mistakes.

For me, the model was fine. It was because I had 2 different versions of entity framework. One version for the web project and another one for the common project which contains the models.

I just had to consolidate the nuget packages.

enter image description here

Enjoy!


i know that this post is late but this solution helped me:

    [Key]
    [Column(Order = 0)]
    public int RoleId { get; set; }

added [Column(Order = 0)] after [Key] can be added by increment by 1:

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

etc...


I too solved this issue in my own project by solving this particular line in my code. I added the following.

[DatabaseGenerated(DatabaseGeneratedOption.None)]

After realizing my mistake I then went and changed it to

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

This further ensures that the field named "Id" increments in value each time a new row is inserted in the database


You don't have to use key attribute all the time. Make sure the mapping file properly addressed the key

this.HasKey(t => t.Key);
this.ToTable("PacketHistory");
this.Property(p => p.Key)
            .HasColumnName("PacketHistorySK");

and don't forget to add the mapping in the Repository's OnModelCreating

modelBuilder.Configurations.Add(new PacketHistoryMap());

Using the [key] didn't work for me but using an id property does it. I just add this property in my class.

public int id {get; set;}

The reason why EF framework prompt 'no key' is that EF framework needs a primary key in database. To declaratively tell EF which property the key is, you add a [Key] annotation. Or, the quickest way, add an ID property. Then, the EF framework will take ID as the primary key by default.


Additionally Remember, Don't forget to add public keyword like this

[Key] 
int RoleId { get; set; } //wrong method

you must use Public keyword like this

[Key] 
public int RoleId { get; set; } //correct method

All is right but in my case i have two class like this

namespace WebAPI.Model
{
   public class ProductsModel
{ 
        [Table("products")]
        public class Products
        {
            [Key]
            public int slno { get; set; }

            public int productId { get; set; }
            public string ProductName { get; set; }

            public int Price { get; set; }
}
        }
    }

After deleting the upper class it works fine for me.


In my case, I was getting the error when creating an "MVC 5 Controller with view, using Entity Framework".

I just needed to Build the project after creating the Model class and didn't need to use the [Key] annotation.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF