简体   繁体   中英

Entity Framework 6 Lazy Loading returns null

I have a class with the following properties

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

if in a method I reference properties of the customer class am getting object null reference exception while BookingCustomerId is populated.ie,

 hotel.BookingCustomerId=2

For instance, string customerFirstName = hotel.BookingCustomer.FirstName; if I peek at the hotel.BookingCustomer i get null How do I go about this Lazy Loading?

If the related entity is coming back as null this means the relationship as understood by entity framework can't find any related entities.

It appears you are using data annotations to flag properties with properties such as foreign keys. You may also need to flag primary keys with the [key] attribute.

You will also need to add a related booking entity to your customer data.

Alternatively you can you the fluent api to do the following in your context.

   // 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);

More on the fluent a picture here: https://msdn.microsoft.com/en-us/data/jj591620.aspx#RequiredToRequired

Lazy loading implies that the related objects are retreived when the getter of that object is used for the first time. At just that time a query to the database is executed to retreive for that object ,for example Hotel.BookingCustomer.

Try to see if the query is indeed executed eg with Sql Server profiler. Examine the query to makes sure everything is correct

If you can't see the query triggered, try to it without the virtual keyword (eager loading) and see if it's working then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM