EntityType has no key defined error

C#.NetEntity Framework

C# Problem Overview


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".

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

  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.

Solution 3 - C#

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.

Solution 4 - C#

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...

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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

Solution 9 - C#

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.

Solution 10 - C#

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!

Solution 11 - C#

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());

Solution 12 - C#

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.

Solution 13 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmateurCoderView Question on Stackoverflow
Solution 1 - C#AmateurCoderView Answer on Stackoverflow
Solution 2 - C#Larry RaymondView Answer on Stackoverflow
Solution 3 - C#BlueRaja - Danny PflughoeftView Answer on Stackoverflow
Solution 4 - C#danigitmanView Answer on Stackoverflow
Solution 5 - C#ChrisSView Answer on Stackoverflow
Solution 6 - C#William BelloView Answer on Stackoverflow
Solution 7 - C#Mayer SpitzView Answer on Stackoverflow
Solution 8 - C#Udara KasunView Answer on Stackoverflow
Solution 9 - C#UtillYouView Answer on Stackoverflow
Solution 10 - C#DanielView Answer on Stackoverflow
Solution 11 - C#ToshView Answer on Stackoverflow
Solution 12 - C#Debendra DashView Answer on Stackoverflow
Solution 13 - C#user11192253View Answer on Stackoverflow