C# 实体框架6延迟加载返回null

C# 实体框架6延迟加载返回null,c#,entity-framework-6,C#,Entity Framework 6,我有一个具有以下属性的类 public class Booking { public long BookingId {get;set;} public string RoomNumber {get;set;} [ForeignKey("BookingCustomer")] public long? BookingCustomerId {get;set;} public virtual Customer BookingCustomer {get;set;}

我有一个具有以下属性的类

public class Booking
{
    public long BookingId {get;set;}
    public string RoomNumber {get;set;}
    [ForeignKey("BookingCustomer")]
    public long? BookingCustomerId {get;set;}

    public virtual Customer BookingCustomer {get;set;}
}

public class Customer
{
    public long CustomerId {get;set;}
    public string FirstName {get;set;}
}
如果在方法I中,在填充BookingCustomerId时,引用customer类的属性得到对象null引用异常,即

 hotel.BookingCustomerId=2
比如说,, 字符串customerFirstName=hotel.BookingCustomer.FirstName; 如果我偷看酒店。预订客户我会得到空值
如何进行这种延迟加载?

如果相关实体返回为null,这意味着实体框架所理解的关系无法找到任何相关实体

您似乎正在使用数据批注来标记具有外键等属性的属性。您可能还需要使用[key]属性标记主键

您还需要向客户数据中添加相关的预订实体

或者,您可以使用fluent api在您的上下文中执行以下操作

   // Configure the primary key for the Booking 
 modelBuilder.Entity<Booking>() 
.HasKey(t => t.BookingID); 

 modelBuilder.Entity<Booking>() 
.HasRequired(t => t.customer) 
.WithRequiredPrincipal(t => t.booking);
//配置预订的主键
modelBuilder.Entity()
.HasKey(t=>t.BookingID);
modelBuilder.Entity()
.HasRequired(t=>t.customer)
.具有所需本金(t=>t.booking);
有关fluent的更多信息,请点击此处:

延迟加载意味着在第一次使用相关对象的getter时检索该对象。 此时将执行对数据库的查询以检索该对象,例如Hotel.BookingCustomer

尝试查看是否确实执行了查询(例如,使用Sql Server profiler)。 检查查询以确保所有内容都是正确的


如果您看不到已触发的查询,请尝试在不使用虚拟关键字(渴望加载)的情况下执行查询,然后查看它是否正常工作。

如果使用渴望加载,客户是否引用了有效的对象?db.Set().Include(“BookingCustomer”).First()是阅读
hotel.BookingCustomer
时的新实体?