Alex Rivera | Logout

EF 4.1 - Model Relationships

Asked 2011-03-18T12:36:51.623
21

I'm trying to create a quick ASP.NET MVC 3 application using the RC version of EF 4.1. I have two models:

public class Race
{
    public int RaceId { get; set; }
    public string RaceName { get; set; }
    public string RaceDescription { get; set; }
    public DateTime? RaceDate { get; set; }
    public decimal? Budget { get; set; }
    public Guid? UserId { get; set; }
    public int? AddressId { get; set; }

    public virtual Address Address { get; set; }
}

and

public class Address
{
    public int AddressId { get; set; }
    public string Street { get; set; }
    public string StreetCont { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public virtual Race Race { get; set; }
}

I get the following error when trying to insert a new Race:

Unable to determine the principal end of an association between the types 'rcommander.Models.Race' and 'rcommander.Models.Address'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Shouldn't it recognize RaceId as the primary key of the Races table and AddressId as the FK to the Addresses table automatically? Am I missing something?

Thanks!

Edit
Report

1 Answer

18

The problem here is 1:1 relation between Address and Race! You probably want to map it as 1:N so you need to modify address to:

public class Address
{
  public int AddressId { get; set; }
  public string Street { get; set; }
  public string StreetCont { get; set; }
  public string City { get; set; }
  public string State { get; set; }
  public string ZipCode { get; set; }

  public virtual ICollection<Race> Races { ... }
}

If you want to use 1:1 then you can't use AddressId in Race but AddressId in Address must be foreign key of Race because entity framework can achive 1:1 only be "sharing" primary key.

answered 2011-03-18T13:30:03.357

Your Answer