在添加新的导航属性时保持原来的FK列

本文关键字:原来 FK 属性 添加 导航 | 更新日期: 2023-09-27 18:04:43

我有类:

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; }
}
在不更改DB模式的情况下,将新属性绑定到现有列的最佳方法是什么?

在添加新的导航属性时保持原来的FK列

首先映射关联:

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注释来解决相同的问题:

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