pomber
pomber

Reputation: 23980

Maintain original FK column when adding new navigation property

I have the classes:

public class Company
{
    public int CompanyId { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

public class Employee
{
    public int EmployeeId { get; set; }
}

Code first migrations creates the following tables:

CreateTable(
    "dbo.Companies",
    c => new
        {
            CompanyId = c.Int(nullable: false, identity: true),
        })
    .PrimaryKey(t => t.CompanyId);

CreateTable(
    "dbo.Employees",
    c => new
        {
            EmployeeId = c.Int(nullable: false, identity: true),
            Company_CompanyId = c.Int(),
        })
    .PrimaryKey(t => t.EmployeeId)
    .ForeignKey("dbo.Companies", t => t.Company_CompanyId)
    .Index(t => t.Company_CompanyId);

Now I want to add the Company property to the Employee class:

public class Employee
{
    public int EmployeeId { get; set; }

    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
}

What is the best way to bind the new property to the existing column without changing the DB schema?

Upvotes: 1

Views: 37

Answers (2)

ocuenca
ocuenca

Reputation: 39346

Agree with the solution proposed by @GertArnold. Following the same idea, you could also use Data annotations to resolve the same problem:

public class Employee
{
    public int EmployeeId { get; set; }

    [ForeignKey("Company"),Column("Company_CompanyId")]
    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
}

Upvotes: 0

Gert Arnold
Gert Arnold

Reputation: 109185

First map the association:

modelBuilder.Entity<Employee>()
            .HasRequired(e => e.Company)
            .WithMany(c => c.Employees)
            .HasForeignKey(e => e.CompanyId);

Then tell EF to map the property CompanyId to the column Company_CompanyId:

modelBuilder.Entity<Employee>().Property(e => e.CompanyId)
            .HasColumnName("Company_CompanyId");

Upvotes: 2

Related Questions