[英]one to zero or one Entityframework navigation property null
I have an context with one to zero or one relationship in entity Framework. 我在实体框架中有一个一对零或一个关系的上下文。 but when i load my entity it will not load the related entity.
但是当我加载我的实体时,它不会加载相关实体。 It allways be null.
始终为空。
Here is my classes: 这是我的课程:
public class Timerow
{
[Key]
public int Id { get; set; }
[Required]
public int BestNo { get; set; }
[Required]
public int PosNo { get; set; }
[Required]
public int EmpNo { get; set; }
public virtual TimerowOvertime TimerowOvertimes { get; set; }
}
public class TimerowOvertime
{
[Key]
[ForeignKey("Timerow")]
public int Id { get; set; }
[Required]
public float Hours { get; set; }
public DateTime? Transfered { get; set; }
public bool Weekend { get; set; }
public bool ATF { get; set; }
[Required]
public virtual Timerow Timerow { get; set; }
}
But when i try to select Timerow and the related timerowOvertimes, timerowOvertimes allways be null. 但是,当我尝试选择Timerow和相关的timerowOvertimes时,timerowOvertimes始终为null。
i try this: 我试试这个:
var timeRows = db.Timerows.ToList();
foreach (var timeRow in timeRows)
{
TimeSheet modelRow = new TimeSheet
{
Id = timeRow.Id,
Date = timeRow.Date,
BestNo = timeRow.BestNo,
PosNo = timeRow.PosNo,
Comment = timeRow.Comment,
Hours = timeRow.Hours,
Ready = timeRow.Ready,
SkillsNoId = timeRow.SkillsNoId
};
if(timeRow.TimerowOvertimes == null)
{
modelRow.ATF = false;
modelRow.Weekend = false;
modelRow.Overtime = 0;
}
else
{
modelRow.Overtime = timeRow.TimerowOvertimes.Hours;
modelRow.ATF = timeRow.TimerowOvertimes.ATF;
modelRow.Weekend = timeRow.TimerowOvertimes.Weekend;
}
}
Anyone has any idea about this? 有人对此有任何想法吗?
You shouldn't have the Id
property in TimerowOvertime
annotated both as [Key]
and [ForeignKey]
. 您不应在
TimerowOvertime
中将Id
属性TimerowOvertime
为[Key]
和[ForeignKey]
。 Currently it looks to bind the Timerow
by using the primary key of TimerowOvertime
entity. 目前,它看起来绑定
Timerow
使用的主键TimerowOvertime
实体。 So you need to extend the TimerowOverTime
entity to contain TimerowId
property and annotate it with the [ForeignKey]
attribute. 因此,您需要扩展
TimerowOverTime
实体以包含TimerowId
属性,并使用[ForeignKey]
属性对其进行注释。
[ForeignKey("Timerow")]
public int TimerowId { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.