Bryan
Bryan

Reputation: 83

Cannot define key for model using mvc3

I'm attempting to set fields in a database using the mvc3 method. When I run the program I get a

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

my model looks like this

public class CarModel
{

    public string VIN { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public string Year { get; set; }
    public string Color { get; set; }
    public string Mileage { get; set; }
    public string Description { get; set; }
}

I've seen where people add a ID, but the database doesnt have an ID property. And when I attempt to add [Key] above the VIN, which is the primary key in the database. It gives an red squiggly error under key.

It seems im missing some reference.

Upvotes: 6

Views: 7318

Answers (2)

Nick Silberstein
Nick Silberstein

Reputation: 833

The reference you're missing is probably System.ComponentModel.DataAnnotations; is this not added for you if you type Ctrl-. with the cursor next to [Key]?

Upvotes: 9

BentOnCoding
BentOnCoding

Reputation: 28158

Entity framework requires each entity to have a Primary Key defined. If you just want to remove the error then add this:

[Key]
public int id { get; set; }

and

public CarModel()
{
    id = 1;
}

Upvotes: 3

Related Questions