Stalli
Stalli

Reputation: 394

EntityType has no key defined. [Key] is presented

Entity

public class Region
{
    [Key]
    public int ID;
    public string Name; 
    public string Description;
}

Model

public class RegionModel
{   [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

Errors

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

Upvotes: 2

Views: 5587

Answers (3)

Christian van R
Christian van R

Reputation: 707

Maybe a strange answer to your problem. But be sure that your project compiles first. i got the same errors when i had added the dataanotations without compiling the project.

I think the code is generated with some kind of reflection.

Upvotes: 0

Bhushan Firake
Bhushan Firake

Reputation: 9448

public class Region
{
    [Key]
    public int RegionId{get;set;}
    public string Name{get;set;} 
    public string Description{get;set;}
}

public class RegionModel
{   [Key]
    public int RegionModelId { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }
}

It works if you have it like ClassNameId.You can even remove [Key] attribute now.

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

Your class fields need to be changed to properties for EF to use the class correctly;

public class Region
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Upvotes: 6

Related Questions