添加新导航属性时保持原始FK列

时间:2015-07-25 18:44:30

标签: c# entity-framework ef-code-first entity-framework-5 ef-migrations

我有课程:

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

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

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

代码首次迁移会创建以下表格:

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);

现在我想将Company属性添加到Employee类:

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

    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
}

在不更改数据库架构的情况下,将新属性绑定到现有列的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

首先映射关联:

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

然后告诉EF将属性CompanyId映射到列Company_CompanyId

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

答案 1 :(得分:0)

同意@GertArnold提出的解决方案。遵循相同的想法,您还可以使用Data annotations来解决同样的问题:

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

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

    public virtual Company Company { get; set; }
}