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



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

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;}
}

如果在我引用客户类属性的方法中,则在填充 BookingCustomerId 时获得对象空引用异常。

 hotel.BookingCustomerId=2

例如 字符串客户名字 = 酒店。预订客户.名字;如果我偷看酒店。预订客户我得到空我该如何进行这种延迟加载?

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

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

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

或者,您可以使用流畅的 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);

更多关于流利图片的信息:https://msdn.microsoft.com/en-us/data/jj591620.aspx#RequiredToRequired

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

尝试查看查询是否确实执行,例如使用 Sql Server 探查器。检查查询以确保一切正确

如果您看不到触发的查询,请尝试在没有 virtual 关键字(预先加载)的情况下进行查询,然后看看它是否有效。

最新更新