我有一個員工,有一份按小時支付的作業,每個小時都有多個考勤卡。我希望工時卡同時鏈接到員工和 Hourly。
public class Employee
{
public int Id { get; set; }
}
public class Hourly
{
public int EmployeeId { get; set; }
public List<Timecard> Timecards{ get; set; }
}
public class Hourly
{
public int HourlyId{ get; set; }
public int EmployeeId { get; set; }
}
如何在 EF 中指定這種關系。
該代碼似乎設定了員工 ID,但會導致遷移出現問題,并且 Hourly 現在設定為 null。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Timecard>()
.HasOne<HourlyPC>()
.WithMany(pc => pc.Timecards)
.HasForeignKey(t => t.EmployeeId)
.HasPrincipalKey(pc => pc.EmployeeId);
}
uj5u.com熱心網友回復:
違反3NF,這意味著重復資料可能導致資料例外等問題。一種技巧是將EmployeeFK包含在Job. 這樣,當 aTimecard有一個 FK to 時Job,它也有一個 FK to Employee。也許你可以在復合材料中使用的作業代碼的第二欄位用于包含JobPK或參考其他物體,它的一個例子是下面其中Position為的歸一化的細節Job的w / o雇員特定資料(例如每小時的速度),并Job涉及一種Employee以aPosition包含員工特定的詳細資訊:
public class Employee
{
public int Id { get; set; }
}
public class Job
{
public int EmployeeId { get; set; }
public Employee Employee { get; set; }
public string PositionId { get; set; }
public Position Position { get; set; }
public ICollection<TimeCard> TimeCards { get; set; }
public decimal HourlyRate { get; set; }
}
public class TimeCard
{
public Id { get; set; }
public int EmployeeId { get; set; }
public Employee Employee { get; set; }
public string PositionId { get; set; }
public Job Job { get; set; }
}
配置:
// configure Job
// configure relationshipt to Position
modelBuilder.Entity<Job>()
.HasOne(j => j.Position)
.WithMany()
.IsRequired();
// configure relationship to Employee
modelBuilder.Entity<Job>()
.HasOne(j => j.Employee)
.WithMany()
.IsRequired();
// create composite PK using the two FK's
modelBuilder.Entity<Job>()
.HasKey(j => new { j.EmployeeId, j.PositionId });
// configure TimeCard
// configure nav prop to Employee
modelBuilder.Entity<TimeCard>()
.HasOne(tc => tc.Employee);
// configure relationship with Job
modelBuilder.Entity<TimeCard>()
.HasOne(tc => tc.Job)
.WithMany(j => j.TimeCards)
.HasForeignKey(tc => new { tc.EmployeeId, tc.PositionId })
.IsRequired();
這可能需要一些調整,但這就是它的具體細節。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381547.html
標籤:实体框架
