Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 & Code First CTP 5 - Missing Key

Can someone make sense of this error?

One or more validation errors were detected during model generation:

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

I have this entity defined:

public class Address
{
    [Key]
    public int ID;

    [Required]
    [MinLength(1)]
    [MaxLength(200)]
    public string Address1 { get; set; }

    [MinLength(1)]
    [MaxLength(200)]
    public string Address2 { get; set; }

    [Required]
    [MinLength(1)]
    [MaxLength(10)]
    public string Zip { get; set; }

    [MinLength(1)]
    [MaxLength(100)]
    public string Province { get; set; }

    public virtual US_State State { get; set; }

    [Required]
    public virtual Country Country { get; set; }
}

My question is: how does the error make any sense for a class that both has a Key attribute data annotation as well as the conventional ID name for its PK.

I would think this class satisfies all rules needed for a meaningful entity to be generated from it.

like image 383
Bent Rasmussen Avatar asked Nov 19 '25 00:11

Bent Rasmussen


1 Answers

Like Craig mentioned, making ID a property will solve your problem.

public int ID { get; set; }

Besides, you don't need the [Key] attribute on ID, it will be recognized as object identifier (i.e. Primary Key) by code first based on conventions.

like image 76
Morteza Manavi Avatar answered Nov 20 '25 14:11

Morteza Manavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!