Skip to main content
 首页 » 编程设计

c#之使用 Entity Framework 4.1,如何使用不同的字段名称配置与复合键的一对多关系

2024年02月23日30kenshinobiy

我有两个表:DeptMaster 和 LaborMaster,其中一个 DeptMaster 有多个 LaborMaster。这些是来自旧数据库的旧表,因此它们不遵循 Code First 命名约定。它们都使用复合键,但每个表中的列名不同。这些类也具有导航属性。我更喜欢用属性映射它们,但如果可能的话请告诉我那个方法,但也要用流畅的方式。

[Table("DeptMaster"), Schema="HR"] 
public partial class DeptMaster 
{ 
    public DeptMaster() 
    { 
         this.LaborMasters = new HashSet<LaborMaster>(); 
    } 
 
    [Key, Column(Order = 0)] 
    public decimal DCompanyNum {get;set;} 
    [Key, Column(Order = 1)] 
    public decimal DDivisionNum {get;set;} 
    [Key, Column(Order = 2)] 
    public decimal DDeptNum {get;set;} 
    public string  DDeptName {get;set;} 
 
    public virtual ICollection<LaborMaster> LaborMasters { get; set; } 
} 
 
[Table("LaborMaster"), Schema="HR"] 
public partial class LaborMaster 
{         
    [Key, Column(Order = 0)] 
    public decimal LCompanyNum {get;set;} 
    [Key, Column(Order = 1)] 
    public decimal LDivisionNum {get;set;} 
    [Key, Column(Order = 2)] 
    public decimal LDeptNum {get;set;} 
    [Key, Column(Order = 3)] 
    public decimal LEmployeeNum {get; set;} 
    public string  LLaborName {get;set;} 
 
    public virtual DeptMaster DeptMaster{ get; set; } 
} 

在我的 OnModelCreating 中,我尝试使用 HasMany,但不清楚我将如何让 Entity Framework 知道当字段不按名称匹配。同样,我更喜欢使用属性,但我不确定是否可行。我对任何一个都持开放态度。谢谢。

请您参考如下方法:

你只需要为前三个属性添加[ForeignKey]属性:

[Table("LaborMaster"), Schema="HR"] 
public partial class LaborMaster 
{         
    [Key, ForeignKey("DeptMaster"), Column(Order = 0)] 
    public decimal LCompanyNum {get;set;} 
    [Key, ForeignKey("DeptMaster"), Column(Order = 1)] 
    public decimal LDivisionNum {get;set;} 
    [Key, ForeignKey("DeptMaster"), Column(Order = 2)] 
    public decimal LDeptNum {get;set;} 
    [Key, Column(Order = 3)] 
    public decimal LEmployeeNum {get; set;} 
    public string  LLaborName {get;set;} 
 
    public virtual DeptMaster DeptMaster{ get; set; } 
} 

或者将 [ForeignKey] 属性放在导航属性上:

    [ForeignKey("LCompanyNum, LDivisionNum, LDeptNum")] 
    public virtual DeptMaster DeptMaster{ get; set; } 

这里属性名称的顺序很重要,它必须遵循列顺序。

使用 Fluent API:

modelBuilder.Entity<DeptMaster>() 
    .HasKey(d => new { d.DCompanyNum, d.DDivisionNum, d.DDeptNum }) 
    .HasMany(d => d.LaborMasters) 
    .WithRequired(l => l.DeptMaster) 
    .HasForeignKey(l => new { l.LCompanyNum, l.LDivisionNum, l.LDeptNum });