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

时间:2018-07-18 08:07:18

标签: c# entity-framework entity-framework-6

我之间存在一对零或一的关系,而我遇到的问题是从属实体到主体实体的导航属性始终为null,除非主体实体首先从其加载DbSet。

数据库关系为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

1 个答案:

答案 0 :(得分:0)

我能够通过将默认构造函数访问器从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; }
}