c# - EF6 可选 1 :1 include not working

标签 c# entity-framework linq eager-loading

尝试设置基本 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 模型一起使用,但我不想这样做。

Schema

最佳答案

您必须构建如下所示的模型。

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/

相关文章:

c# - 调用 format-number XPath 函数时,收到错误 : "Namespace Manager or XsltContext needed."

c# - 如何在 C# 中使用索引设置结构的特定成员

C# - 按列拆分 CSV 文件

entity-framework - 使用 ef 在数据库中使用没有时间的日期

asp.net - EF、UoW 和存储库 - 何时在 WebForms 中处理 UnitOfWork?

c# - 等号传递的是引用还是对象副本?

xml - Entity Framework 查询 Xml

c# - 查询主体必须以 select 子句或 group 子句结尾为什么这里会出错?

c# - LINQ 按特定列返回不同值

c# - 如何在 Entity Framework 查询中使用左连接?