问题
I have two tables: DeptMaster and LaborMaster where one DeptMaster has many LaborMasters. These are legacy tables from an old database so they don't follow Code First naming conventions. They both use composite keys but with different column names in each table. The classes have navigational properties as well. I would prefer mapping them with attributes but please show me that method if possible but also the fluent way.
[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; }
}
In my OnModelCreating, I attempted to use the HasMany but it is not clear how I will make Entity Framework know how LCompanyNum, LDivisionNum, and LDeptNum of the child points back to DCompanyNum, DDivisionNum, and DDeptNum of the parent when the fields do not match by name. Again, I would prefer using attributes but I'm not sure if it's possible. I'm open to either. Thank You.
回答1:
You just need to add the [ForeignKey]
attribute for the first three properties:
[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; }
}
Or alternatively put the [ForeignKey]
attribute on the navigation property:
[ForeignKey("LCompanyNum, LDivisionNum, LDeptNum")]
public virtual DeptMaster DeptMaster{ get; set; }
Here the order of the property names matters, it must follow the column order.
With 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 });
来源:https://stackoverflow.com/questions/9573043/using-entity-framework-4-1-how-do-i-configure-one-to-many-relationship-with-com