Search code examples
entity-frameworkentity-framework-4entity-framework-ctp5

EF4 CTP5 one to one mapping with existing database


So I have an existing database with a Users table and an Airports table each with a primary key names ID. The Users table has a nullable column DefaultAirportID which is a fk to the ID of the Airports table.

Here are my POCOs:

public class User : IEntity
{
    [Key]
    [Required]
    public int ID { get; set; }

    public int? DefaultAirportID { get; set; }        
    public Airport DefaultAirport { get; set; }

    ...
}

public class Airport : IEntity
{
    [Key]
    [Required]
    public int ID { get; set; }

    ...
}

I keep getting the error "Invalid column name 'AirportID'.". What do I need to do to get it to populate the DefaultAirport object?


Solution

  • You need to use fluent API to configure your association:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
                    .HasOptional(x => x.DefaultAirport)
                    .WithMany()
                    .HasForeignKey(n => n.DefaultAirportID);        
    }