Entity Framework 6 Lazy Loading returns null

c# entity-framework-6

Question

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.i.e.,

 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?

1
0
1/24/2015 9:59:38 AM

Popular Answer

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 e.g. 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.

0
1/24/2015 2:30:48 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow