繁体   English   中英

EF6必需与可选的关系(一对零或一对)无法正常工作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM