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.

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

2 Answers2

10

Navigation properties (refering to other entities) on a complex type are not supported. You must either make your Location an entity (with its own table) or remove the navigation property Country from Location (and add the [ComplexType] attribute as mentioned by Steve Morgan).

Edit

Reference: http://msdn.microsoft.com/en-us/library/bb738472.aspx

"Complex type cannot contain navigation properties."

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • But what about the `CountryID` integer inside `Location` class? Is it possible to make that a foreign key constraint? (I have a similar problem and can't get it to work) – Isak Savo Sep 30 '11 at 06:55
  • @Isak: No it is not possible. If you want to have it FK in database you must do it in database directly but EF will not reflect it. – Ladislav Mrnka Sep 30 '11 at 09:22
  • 1
    The fact that this is not supported is mentioned directly in Complex type description on MSDN: http://msdn.microsoft.com/en-us/library/bb738472.aspx – Ladislav Mrnka Sep 30 '11 at 09:25
  • @Ladislav: Thanks for the reference! I've copied it into the answer. – Slauma Sep 30 '11 at 10:55
  • @LadislavMrnka: ok, thanks. I was half hoping that it would be possible to specify on the parent class (i.e. the actual entity) through the fluent API but I guess not (I couldn't make it work though) – Isak Savo Sep 30 '11 at 11:43
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.

Steve Morgan
  • 12,978
  • 2
  • 40
  • 49