Alex Rivera | Logout

EF-Code first complex type with a navigational property

Asked 2011-09-29T20:25:12.470
12

My Model:

public class Country
{
    public int CountryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

public class Location
{
    public string Address { get; set; }

    public virtual int CountryId { get; set; }
    public virtual Country Country { get; set; }
}    

public class User{

    protected User()
    {
        Location = new Location();
    }

    public int UserId { get; set; }
    public Location Location { get; set; }

}

When generating the database, I get:

One or more validation errors were detected during model generation:

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

How do I have a navigational property inside a complex type? If I remove the country navigational property, it works fine.

Edit
Report

1 Answer

3

EF wants to infer a primary key for Location, but can't.

Add a public int LocationId { get; set; } to the Location class and it should be happy.

If you want to use Location as a complex type, annotate it with a [ComplexType] attribute.

answered 2011-09-29T20:29:46.170

Your Answer