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

Maintain original FK column when adding new navigation property

我有 classes:

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

现在我想将公司 属性 添加到员工 class:

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

    public int CompanyId { get; set; }

    public virtual Company Company { get; set; }
}

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

先映射协会:

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

同意@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; }
}