EntityType 'Category' has no key defined. Define the key for this EntityType

asp.net-mvc entity-framework

Question

Developing a basic ASP.net MVC 4 application. Its a simple product catalog application, where in I have 2 database tables ('Category' and 'Products')

There is a foreign key reference of 'Category id' (primary key in Category table) in 'Products' table.

When I run the application, I am getting error message (listed below).

System.Data.Entity.Edm.EdmEntityType: : EntityType 'Category' has no key defined. Define the key for this EntityType.

System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Category' is based on type 'Category' that has no keys defined

This looks like a common error for newbies,I did check all the related solutions to 'Entity key '' has no key defined.' but still my problem is not solved, Kindly help me in understanding this problem and what is the correct solution to this problem.

Below are my model classes

Category.cs

namespace ChemicalStore.Models
{
    public partial class Category
    {
        public int CatId { get; set; }
        public string CatName { get; set; }
        public string CatDescription { get; set; }
        public List<Product> Product { get; set; }
    }     
}

Products.cs

namespace ChemicalStore.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public int CatId { get; set; }
        public string ProductTitle { get; set; }
        public string ProductPrice { get; set; }
        public string ProductDescription { get; set; }
        public string ProductPackage { get; set; }
    }
}
1
35
6/23/2016 1:30:44 AM

Accepted Answer

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; }
    }
}
166
12/1/2013 4:36:34 PM

Popular Answer

  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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow