【问题标题】:EF6 Required-to-Optional Relationship (One-to–Zero-or-One) not working correctlyEF6 必需-可选关系(一对零或一)无法正常工作
【发布时间】:2018-07-18 08:07:18
【问题描述】:

我有一对零或一的关系,我遇到的问题是依赖实体到主体实体的导航属性始终为空,除非首先从其加载主体实体数据库集。

数据库关系是 Employee.ID -> TrainerProfile.TrainerID,其中 TrainerID 是主键和外键。

实体是 Employee.Id -> TrainerProfile.Id 映射到 [Column] 属性。

//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

【问题讨论】:

  • 请显示您看到“主体实体始终为空”的代码。
  • @GertArnold 我已经更新了示例。
  • 除非在上下文中禁用延迟加载 profile.Employee 应在访问时加载,无论是在代码中还是在调试器中。那么,延迟加载是否被禁用?
  • @GertArnold 延迟加载已启用。它以前可以工作,但 TrainerProfile.Id 是 TrainerProfile.TrainerID。

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


【解决方案1】:

我能够通过将默认构造函数访问器从私有更改为受保护来解决该问题。

//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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2016-09-20
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多