EntityFramework:如何从数据库加载对象列表?

tom*_*mus 1 c# entity-framework

我有两个实体:

public class Booking
{
    [Key]
    public int Id { get; set; }

    public int RoomId { get; set; }
    [ForeignKey("RoomId")]
    public Room Room { get; set; }

    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DocumentNumber { get; set; }
    public string ContactPhone { get; set; }
}

public class Room
{
    [Key]
    public int RoomId { get; set; }
    public int Number { get; set; }

    public int Size { get; set; }
    public bool HasBalcony { get; set; }

    public int Beds_1 { get; set; }
    public int Beds_2 { get; set; }
    public double DayPrice { get; set; }

    public List<Booking> Bookings { get; set; }
    ...

    public int BookingsCount()
    {
        return Bookings.Count;
    }

    public bool IsFree(DateTime dateTime)
    {
       MessageBox.Show(BookingsCount().ToString());
       return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

和数据库上下文:

public class HotelContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Room> Rooms { get; set; }
    public DbSet<Booking> Bookings { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Booking>()
        .HasRequired(b => b.Room)
        .WithMany(r => r.Bookings)
        .HasForeignKey(b => b.RoomId);
    }
}
Run Code Online (Sandbox Code Playgroud)

调用 MessageBox.Show 时出现异常: Hotel.exe 中发生类型为“System.NullReferenceException”的未处理异常

当我尝试访问 Room::Bookings 时,该列表始终为空。Bookings 表中有一行,Rooms 表中有多行。如何将所有 Bookings 加载到 Room 对象中?

AAA*_*ddd 8

取决于您处于学习曲线的哪个阶段,但是有些事情很突出

首先

您要么想通过FluentApiAnnotations创建关系,而不是两者都创建

IE。你的 Room 实体上有这个

[ForeignKey("RoomId")]
Run Code Online (Sandbox Code Playgroud)

这是流利的

 modelBuilder.Entity<Booking>()
    .HasRequired(b => b.Room)
    .WithMany(r => r.Bookings)
    .HasForeignKey(b => b.RoomId);
Run Code Online (Sandbox Code Playgroud)

Booking您需要选择其中之一,否则您的ieRoomId和ie 中可能会出现多个 IdRoom_Id

第二

如果您希望能够延迟加载, bookings您需要进行Bookings收集Virtual

public virtual List<Booking> Bookings { get; set; }
Run Code Online (Sandbox Code Playgroud)

最后

访问您的数据(假设您的连接字符串正确)

using(var db = new HoteContext())
{
    var rooms = db.Rooms.Include(x => x.Bookings).ToList();
}
Run Code Online (Sandbox Code Playgroud)

注意:虽然 EF Lazy 加载关系,但您可能需要确保已包含该Room->Booking关系