[英]EF6 Optional 1:1 include not working
嘗試設置基本的 EF6 可選 1:1。 非常令人沮喪。 我已經閱讀了很多並且丟失了帖子。
我有兩個實體,Guests 和 Seats,每個實體都可以獨立存在,一個座位不需要客人,客人不需要座位。
嘉賓模特:
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 可選沒有加載相關數據。
根據要求,這是生成的模式……這里肯定發生了一些奇怪的事情。 作為旁注,我可以讓它與視圖模型一起工作,但我不想。
1-0..1 關系配置和你想要的方式不一樣。
根據上面提到的規則,你的代碼應該如下
嘉賓班
public class Guest
{
public int ID { get; set; }
[Required]
public string FirstName { get; set; }
public IList<Seat> Seats { get; set; }
}
座位等級
public class Seat
{
public int ID { get; set; }
[Required]
public string SeatNumber{ get; set; }
public IList<Guest> Guests { get; set; }
}
連接表
public GuestSeat
{
public int GuestID{get;set;}
public int SeatID{get;set;}
public DateTime ReservedDate{get;set;}
// other fields goes here
}
配置
modelBuilder.Entity<GuestSeat>()
.HasKey(gs => new {gs.GuestID,gs.SeatID})
.ToTable("GuestSeats");
modelBuilder.Entity<GuestSeat>()
.HasRequired(g=>g.Guest)
.WithMany(g=>g.Seats)
.HasForeignKey(gs =>gs.GuestID)
.DeleteOnCascade(false);
modelBuilder.Entity<GuestSeat>()
.HasRequired(s=>s.Seat)
.WithMany(s=>s.Guests)
.HasForeignKey(gs =>gs.SeatID)
.DeleteOnCascade(false);
該解決方案提供以下
SeatID
和ReservedDate
創建唯一索引。希望能幫到你
您必須構建您的模型,如下所示。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.