Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.2, CodeFirst - Navigation property within a complext type

I know I can solve this by pushing everything into a single entity rather than nesting complex types (as they are just 1-1 mappings), but I like the way it groups properties in the generated OM.

I have a Customer entity that contains a complext type "CrmData". The CrmData entity has a complex type of address.

public class Customer {
  [Required]
  public CrmSpecificData CrmData { get; set; }
}
[ComplexType]
public class CrmSpecificData {
  [MaxLength(40)]
  public string FirstName { get; set; }

  [MaxLength(80)]
  public string LastName { get; set; }

  public Address Address { get; set; }
}
[ComplexType]
public class Address {
  [MaxLength(150)]
  public string Address1 { get; set; }

  [MaxLength(150)]
  public string Address2 { get; set; }

  [MaxLength(100)]
  public string City { get; set; }

  [MaxLength(15)]
  public string PostalCode { get; set; }

  public StateProvince StateOrProvince { get; set; }

  public virtual CountryRegion CountryOrRegion { get; set; }
}

The StateProvince & CountryRegion types are entities in my DB (similar to how the AdventureWorks sample DB works). The problem is that when EF tries to create the model, it fails with:

The type 'MyCo.Crm.Entities.StateProvince' has already been configured as an entity type. It cannot be reconfigured as a complex type..

I've tried making the StateProvince a complex type but that doesn't resolve the issue. Ideas?

public class StateProvince {
  [Key]
  public int StateProvinceId { get; set; }

  [MaxLength(3)]
  public string StateProvinceCode { get; set; }

  [MaxLength(50)]
  public string Name { get; set; }
}
like image 464
Andrew Connell Avatar asked Dec 23 '11 12:12

Andrew Connell


1 Answers

Complex types cannot contain navigation properties. Navigation properties can be defined only in entity. So you must either:

  • Use table splitting instead of complex types but it would result in another problems - for example you will not be able to nest those types and you will have to use eager / lazy loading to load them.
  • Move all navigation properties to the main entity
like image 131
Ladislav Mrnka Avatar answered Nov 11 '22 19:11

Ladislav Mrnka