Reputation: 605
Using EF4 against a SQL Server database for one of our current projects and have hit a performance issue. Say I have the Book and Author classes below (not compiled but just for the purpose of the example).
public class Book
{
public Author Author { get; set; }
}
public class Author
{
public List<Book> Books { get; set; }
}
A book can be loaded easily however when an Author is assigned to a book as per below, a query is run to find all books for the author even though the Books property is never explicitly accessed
In our real-world example (not books and authors) this can load up thousands of objects that will never be used. There are no fancy getters/setters that could be triggering this.
Any ideas on what could be causing the problem? The query isn't run when the Books list is removed but it may be legitimately used in some scenarios.
Thanks, John
Upvotes: 0
Views: 67
Reputation: 56
If you are using Entity Framework, then any related property that is not marked as "virtual" will be loaded when the object is first created. If you don't want to automatically load the Books property for an Author, then just update your code like this:
public class Book
{
public Author Author { get; set; }
}
public class Author
{
public virtual List<Book> Books { get; set; }
}
For more information about Eager Loading vs. Lazy Loading see... http://msdn.microsoft.com/en-us/data/jj574232.aspx
Upvotes: 1