[英]EF6 Required-to-Optional Relationship (One-to–Zero-or-One) not working correctly
我之間存在一對零或一對的關系,而我遇到的問題是,除非首先從其DbSet加載主體實體,否則從屬實體到主體實體的導航屬性始終為null。
數據庫關系為Employee.ID-> TrainerProfile.TrainerID,其中TrainerID為主鍵和外鍵。
實體是用[Column]屬性映射的Employee.Id-> TrainerProfile.Id。
//Principal
public class Employee : BaseEntity<int>
{
[Key]
[Column("ID")]
public override int Id { get; protected set; }
[Required(ErrorMessage = "A Username is required")]
[DataType(DataType.Text)]
[StringLength(256)]
public string UserName { get; set; }
[Required(ErrorMessage = "A First Name is required")]
[StringLength(40)]
public string FName { get; set; }
[Required(ErrorMessage = "A Last Name is required")]
[StringLength(40)]
public string LName { get; set; }
...
}
//Dependent
public class TrainerProfile : BaseEntity<int>
{
private TrainerProfile()
{
}
protected TrainerProfile(int id) : base(id)
{
}
[Key]
[Column("TrainerID")]
public override int Id { get; protected set; }
public bool Passport { get; set; }
[StringLength(1000)]
public string SpecialConsiderations { get; set; }
[StringLength(10)]
public string SeatPreference { get; set; }
[ForeignKey("Id")]
public virtual Employee Employee { get; set; }
}
//DBContext OnModelCreating()
modelBuilder.Entity<Employee>()
.HasOptional(e => e.TrainerProfile)
.WithRequired(e => e.Employee);
modelBuilder.Entity<TrainerProfile>()
.HasKey(e => e.Id)
.HasRequired(e => e.Employee)
.WithOptional(e => e.TrainerProfile);
更新
var db = new DBContext();
var profile = db.TrainerProfiles.First(); //profile.Employee null
var employee = db.Employees.List(); //profile.Employee now loaded
我可以通過將默認構造函數訪問器從private更改為protected來解決此問題。
//Dependent
public class TrainerProfile : BaseEntity<int>
{
protected TrainerProfile() //***Changed from private to protected***
{
}
protected TrainerProfile(int id) : base(id)
{
}
[Key]
[Column("TrainerID")]
public override int Id { get; protected set; }
public bool Passport { get; set; }
[StringLength(1000)]
public string SpecialConsiderations { get; set; }
[StringLength(10)]
public string SeatPreference { get; set; }
[ForeignKey("Id")]
public virtual Employee Employee { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.