尝试设置基本 EF6 可选 1:1。非常令人沮丧。我读了很多帖子并丢失了。
我有两个实体,客人和座位,每个实体都可以独立存在,座位不需要客人,客人也不需要座位。
客座模特:
public int ID { get; set; }
public int? SeatID { get; set; }
[Required]
public string FirstName { get; set; }
//Link to Seat
public Seat Seat { get; set; }
座椅型号:
public int ID { get; set; }
public int? GuestID { get; set; }
[Required]
public string SeatNumber { get; set; }
public bool Occupied { get { return (GuestID == null ? true : false); } }
//Link to Guest
public Guest Guest{ get; set; }
我在走到这一步时遇到了很多问题。我必须将其添加到我的模型创建中才能使关系发挥作用:
modelBuilder.Entity<Seat>()
.HasOptional(g => g.Guest)
.WithOptionalDependent(s => s.Seat);
现在我的应用程序正在运行,但是当我尝试使用 include 方法加载相关数据时,它只是显示为空白,什么也没有。
var seats = db.Seats.Include(s => s.Guest);
return View(seats.ToList());
根据我的观点,我使用
@Html.DisplayFor(modelItem => item.Guest.FirstName)
我想知道如何使 include 语句起作用,最好不要延迟加载(或者即使必须的话)。另外,我不想有 SeatAssignment 表,我考虑过沿着这条路走。
我可以使用 Viewmodel 来实现此目的,但我不明白为什么 1:1 选项没有加载相关数据。
根据要求,这是生成的模式...这里肯定发生了一些奇怪的事情。作为旁注,我可以使其与 View 模型一起使用,但我不想这样做。
最佳答案
您必须构建如下所示的模型。
public class Guest
{
public int GuestId { get; set; }
[Required]
public string FirstName { get; set; }
//Link to Seat
public virtual Seat Seat { get; set; }
}
public class Seat
{
public int SeatId { get; set; }
[Required]
public string SeatNumber { get; set; }
public bool Occupied { get { return (GuestID == null ? true : false); }}
//Link to Guest
public virtual Guest Guest{ get; set; }
}
流畅的 API 映射:
modelBuilder.Entity<Seat>()
.HasOptional(g => g.Guest)
.WithOptionalDependent(s => s.Seat);
然后:
var seats = db.Seats.Include(s => s.Guest).ToList();
关于c# - EF6 可选 1 :1 include not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940772/