Peter
Peter

Reputation: 803

Creating Primary Key field on MVC class

I am new to MVC and C#. I just stumbled on it and found it interesting. I encountered an issue which will not allow me proceed. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 

namespace MyHotel.Models
{
    public class AccountTypes
    {
        public int AccountTypeID { get; set; }
        public string AccountTypeName { get; set; }
    }
}

I created the controler and the view thereafter.

And for this, I keep got this error:

One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'AccountTypes' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet "AccountTypes" is based on type "AccountTypes" that has no keys defined.

I google that the answers were to add [Key] over the public int AccountTypeID { get; set; } so it could look like this:

namespace MyHotel.Models
{
    public class AccountTypes
    {
        [Key]
        public int AccountTypeID { get; set; }
        public string AccountTypeName { get; set; }
    }
}

But no result until now. Note: I am using MVC 4

Upvotes: 19

Views: 75445

Answers (4)

Shaharukh Pathan
Shaharukh Pathan

Reputation: 21

   public class MyDbContext : DbContext
 {
  public DbSet<AccountTypes> AccountTypes { get; set; } 

    protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
    modelBuilder.Entity<AccountTypes>().HasKey(x => x.AccountTypeID);
    base.OnModelCreating(modelBuilder);
   }
   }

Upvotes: 0

user3137281
user3137281

Reputation: 1

Hi Peter it seens you are missing an "s"

Your Account int should be:

public int AccountsTypeID { get; set; }

Hope it can be solved; Fernando.

Upvotes: -3

dknaack
dknaack

Reputation: 60556

Description

Entity Framework CodeFirst recognize the key, by default, by name. Valid names are Id or <YourClassName>Id.

Your property should named Id or AccountTypesId

Another way is to use the ModelBuilder to specify the key.

Sample

public class MyDbContext : DbContext
{
    public DbSet<AccountTypes> AccountTypes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AccountTypes>.HasKey(x => x.AccountTypeID);
        base.OnModelCreating(modelBuilder);
    }
}

Mode Information

Upvotes: 25

SaravananArumugam
SaravananArumugam

Reputation: 3720

Try using [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] property to indicate the key field.

The regular field would go with EntityKeyPropert=false.

Upvotes: 1

Related Questions