Error while generating Model in MVC - asp.net-mvc

I got the following error while generating a Model in ASP.Net:
MvcApplication1.Models.Department: : EntityType 'Department' has no key defined. Define the key for the EntityType.
department: EntityType: EntitySet 'department' is based on type 'Department' that has no keys define.
Here's a screenshot with more details:
I added the primary key to the Department table:
{
[Table("department")]
public class Department
{
public int dept id { get; set; }
public string department { get; set; }
public List<Employee> Employees { get; set; }
}
}

You need to add a [key] annotation to your deptid field:
{
[Table("department")]
public class Department
{
[Key]
public int deptid { get; set; }
public string department { get; set; }
public List<Employee> Employees { get; set; }
}
}

department table. ' {
[Table("department")]
public class Department
{
[Key]
public int dept id { get; set; }
public string department { get; set; }
public List<Employee> Employees { get; set; }
}
}`
Add key attribute, refer msdn

Another option is to change public int deptid to either public int Id or public int DepartmentId. This is a built-in EF convention, and if you use this syntax, you don't need the [Key] attribute.
https://msdn.microsoft.com/en-us/library/jj679962(v=vs.113).aspx#Anchor_1

Related

An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll

Error-An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: One or more validation errors were detected during model generation:
MVCApplication.Models.Employee: : EntityType 'Employee' has no key defined. Define the key for this EntityType.
Employees: EntityType: EntitySet 'Employees' is based on type 'Employee' that has no keys defined.
controller code:
namespace MVCApplication.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Detail(int id)
{
EmployeeContext employeecontext = new EmployeeContext();
Employee emp = employeecontext.Employees.Single(x => x.Emp_Id ==id);//here its throwing an exception
return View("employee",emp);
}
}
this is my model employee class:
namespace MVCApplication.Models
{
[Table("Employee")]
public class Employee
{
public int Emp_Id { get; set; }
public string Emp_Name { get; set; }
public string Designation { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
}
this is my employee context class:
namespace MVCApplication.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
You have to set attribute [Key] to your model, like this
[Table("Employee")]
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Emp_Id { get; set; }
public string Emp_Name { get; set; }
public string Designation { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
Use [DatabaseGenerated(DatabaseGeneratedOption.Identity)] only if your database generate ids, if not you just [Key] attribute.
Make sure that you have set the auto increment attribute to 'Emp_Id' column in your database table, and your model should look like this:
[Table("Employees")]
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Emp_Id { get; set; }
public string Emp_Name { get; set; }
public string Designation { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}

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

i Have a Model Class
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<SelectListItem> CourseList { get; set; }
}
and the
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
and i try ti use it as
List<Student> sList = db.Students.ToList();
and i am getting following error
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'SelectListItem' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'SelectListItems' is based on type 'SelectListItem' that has no keys defined.
Please suggest where i am doing wrong.
Add [NotMapped] annotation to the LIST class
[NotMapped]
public List<SelectListItem> ListItems { get; set; }
NotMapped Code first convention dictates that every property that is of a supported data type is represented in the database. But this isn’t always the case in your applications. For example you might have a property in the Blog class that creates a code based on the Title and BloggerName fields. That property can be created dynamically and does not need to be stored. You can mark any properties that do not map to the database with the NotMapped annotation such as this BlogCode property.
[NotMapped]
public string BlogCode
{
get
{
return Title.Substring(0, 1) + ":" + BloggerName.Substring(0, 1);
}
}
You can refer to the link here on EF code first Data Annotations
You should not be attempting to store SelectListItem in the database, as this is MVC specific concept. Instead create a custom entity class and use it instead;
public class Course
{
public int CourseId { get; set; }
public string CourseTitle { get; set; }
}
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public ICollection<Course> CourseList { get; set; }
}
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
}

Razor/MVC 3 Entity Framework Error Regarding Primary Key

I'm using VS 2010 with Razor/MVC 3 to create a form where User 1 submits information to a database using RequestQueue Model (this is just a queue table). User 2 then pulls this information, approves it, and the data is sent to the main database via DbRequestForm Model. This model, however, consists of several sub-models (Data_Dictionary, SERVER_DATABASE, and DatabaseRequestInfo) because the submitted data needs to go to three separate tables.
The problems is, whenever I approve the data for submission from RequestQueue to DbRequestForm, I get an error saying there is no primary key for DbRequestForm. However, there is a PK for each sub-model. I have also tried adding [Key] public int SrvrDB_ID { get; set; } and other variations to DbRequestForm to no avail.
Initial Model:
public class RequestQueue
{
[Key]
public int SrvrDB_ID { get; set; }
public string dbName { get; set; }
public int InitialSpaceNeeded { get; set; }
public string ScheduledJobSetup { get; set; }
public string PII_data { get; set; }
}
Encapsulating Model:
public class DbRequestForm
{
public Data_Dictionary Data_Dictionary { get; set; }
public DatabaseRequestInfo DatabaseRequestInfo { get; set; }
public SERVER_DATABASE SERVER_DATABASE { get; set; }
}
Models based on final three tables:
public class Data_Dictionary
{
[Key]
public int SrvrDB_ID { get; set; }
public string PII_data { get; set; }
}
public class SERVER_DATABASE
{
[Key]
public int SrvrDB_ID { get; set; }
public string dbName { get; set; }
}
public class DatabaseRequestInfo
{
[Key]
public int SrvrDB_ID { get; set; }
public int InitialSpaceNeeded { get; set; }
public string ScheduledJobSetup { get; set; }
}
Any ideas how to avoid this error? Thanks in advance!
EDIT: The specific error is '
System.Data.Edm.EdmEntityType: : EntityType 'DbRequestForm' has no key
defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet DbRequestForms is
based on type DbRequestForm that has no keys '
The error tells that you need to define key for DBRequestForm.
Code First would infer that a property is a primary key if the property is called ‘Id’ or ‘class name Id’.
In your case you have to add
[Key]
public int DBRequestFormId { get; set; }
This concrete error won't appear anymore.
here is detailed information how code first works
http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-code-first.aspx
see the Primary Key section

MVC No Key Defined

I am getting this error in my MVC Application:
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'CustomerModel' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Customer� is based on type �CustomerModel� that has no keys defined.
My Customer Model looks like this:
public class CustomerModel
{
public string Name { get; set; }
public int CustomerID { get; set; }
public string Address { get; set; }
}
public class CustomerContext : DbContext
{
public DbSet<CustomerModel> Customer { get; set; }
}
By default, Entity Framework assumes a key property called Id exists in your model class. Your key property is called CustomerID, so Entity Framework can't find it.
Either change the name of your key property from CustomerID to Id, or decorate the CustomerID property with the Key attribute:
public class CustomerModel
{
public string Name { get; set; }
[Key]
public int CustomerID { get; set; }
public string Address { get; set; }
}
public class CustomerContext : DbContext
{
public DbSet<CustomerModel> Customer { get; set; }
}

EntityType 'ApplicantPosition' has no key defined

When running my first asp.net mvc application I got this error
I thought that entity framework automatically would create the keys of column names that end with Id? isnt it correct?
As you can see the ApplicantPositionID would be a table with 2 columns as primary key because it would relate to Applicants and also to Position.
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'ApplicantImage' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntityType: : EntityType 'ApplicationPositionHistory' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �ApplicantsPositions� is based on type �ApplicantPosition� that has no keys defined.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �ApplicantImages� is based on type �ApplicantImage� that has no keys defined.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �ApplicationsPositionHistory� is based on type �ApplicationPositionHistory� that has no keys defined.
The error is thrown in this line:
public ActionResult Index()
{
return View(db.Positions.ToList());
}
And my model is the following one:
namespace HRRazorForms.Models
{
public class Position
{
public int PositionID { get; set; }
[StringLength(20, MinimumLength=3)]
public string name { get; set; }
public int yearsExperienceRequired { get; set; }
public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
}
public class Applicant
{
public int ApplicantId { get; set; }
[StringLength(20, MinimumLength = 3)]
public string name { get; set; }
public string telephone { get; set; }
public string skypeuser { get; set; }
public ApplicantImage photo { get; set; }
public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
}
public class ApplicantPosition
{
public int ApplicantID { get; set; }
public int PositionID { get; set; }
public virtual Position Position { get; set; }
public virtual Applicant Applicant { get; set; }
public DateTime appliedDate { get; set; }
public int StatusValue { get; set; }
public Status Status
{
get { return (Status)StatusValue; }
set { StatusValue = (int)value; }
}
//[NotMapped]
//public int numberOfApplicantsApplied
//{
// get
// {
// int query =
// (from ap in Position
// where ap.Status == (int)Status.Applied
// select ap
// ).Count();
// return query;
// }
//}
}
public class ApplicantImage
{
public int ApplicantId { get; private set; }
public byte[] Image { get; set; }
}
public class Address
{
[StringLength(20, MinimumLength = 3)]
public string Country { get; set; }
[StringLength(20, MinimumLength = 3)]
public string City { get; set; }
[StringLength(20, MinimumLength = 3)]
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
}
public class ApplicationPositionHistory
{
public ApplicantPosition applicantPosition { get; set; }
public Status oldStatus { get; set; }
public Status newStatus { get; set; }
[StringLength(500, MinimumLength = 10)]
public string comments { get; set; }
public DateTime dateModified { get; set; }
}
public enum Status
{
Applied,
AcceptedByHR,
AcceptedByTechnicalDepartment,
InterviewedByHR,
InterviewedByTechnicalDepartment,
InterviewedByGeneralManager,
AcceptedByGeneralManager,
NotAccepted
}
}
EF Code First can only infer that a property is a primary key if the property is called Id or <class name>Id (or if it is annotated with the Key attribute).
So you need to extend your e.g. ApplicantImage with an ApplicantImageId or Id property etc.
Edit: An artice about the coneventions: Conventions for Code First
You can add the [Key] atributte to the property ApplicantId or do it via Fluent API overriding OnModelCreating method DbContext
modelBuilder.Entity<ApplicantImage >().HasKey(p => p.ApplicantId);
In your case, EF naming convention first looks for an ID (case-insensitive) column. If nothing, looks for ApplicantImageId and when it founds nothing, it raises that error.
So, you should add the [Key] attribute on your ID:
public class ApplicantImage
{
[Key]
public int ApplicantId { get; private set; }
public byte[] Image { get; set; }
}
and if ApplicantId column is identity in your database, you should add another attribute too:
public class ApplicantImage
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ApplicantId { get; private set; }
public byte[] Image { get; set; }
}
I know this is an old question but it is still relevant. I ran into the same situation however we use a .tt file to generate the .cs from our edmx. Our .tt is setup to add the [Key] attribute on our first column of the table for most situations, but in my case i was using a row over () in SQL to generate unique id's for the first column (works great for most situations). The problem with that was it makes a nullable and the .tt wasn't setup to add [Key] in this case.
Wrapping the row Over() in a ISNULL ((),0) was able to fix making the column not null and solved my problem. Otherwise, as mentioned by marianosz, simply using the .HasKey() in your data context will work fine too.

Resources