Database Reference
In-Depth Information
As you may have already noticed, classes in our entity model reference each other. For example, Customer and
OrderItems are defined as the properties in the Orders class. By default, Entity Framework uses lazy loading and does
not load them until those attributes are requested by the client.
Lazy loading improves the performance of the system because attributes are not loaded unless the application
needs them. However, it can make objects logically inconsistent, because data is loaded at different times. Consider
the situation where an application uses lazy loading to load a list of OrderItems for an Order . If another user changed
the Order and added another OrderItem row, the loaded list would be inconsistent with the Order object loaded
previously by the application.
You can disable lazy loading through the Configuration.LazyLoadingEnabled property or, alternatively, you can
force Entity Framework to load all of the attributes with the object. Listing 16-10 shows such an example. The code
loads the Order object with a specific OrderId including Customer and Items attributes.
Listing 16-10. Loading attributes with the main object
var order = context.Orders.Include("Customer").Include("Items")
.Where(t => t.OrderId == 1).First();
Even though it looks very simple in the client code, the SELECT statement generated by Entity Framework could
surprise you. Listing 16-11 demonstrates this occurrence.
Listing 16-11. Loading attributes with main object: Generated SQL
SELECT
[Project1].[OrderId] AS [OrderId],
[Project1].[CustomerId] AS [CustomerId],
[Project1].[OrderNo] AS [OrderNo],
[Project1].[CustomerId1] AS [CustomerId1],
[Project1].[FirstName] AS [FirstName],
[Project1].[LastName] AS [LastName],
[Project1].[Email] AS [Email],
[Project1].[LastPurchaseDate] AS [LastPurchaseDate],
[Project1].[CreditLimit] AS [CreditLimit],
[Project1].[Photo] AS [Photo],
[Project1].[C1] AS [C1],
[Project1].[OrderItemId] AS [OrderItemId],
[Project1].[OrderId1] AS [OrderId1],
[Project1].[Qty] AS [Qty],
[Project1].[Price] AS [Price]
FROM (
SELECT
[Limit1].[OrderId] AS [OrderId],
[Limit1].[CustomerId1] AS [CustomerId],
[Limit1].[OrderNo] AS [OrderNo],
[Limit1].[CustomerId2] AS [CustomerId1],
[Limit1].[FirstName] AS [FirstName],
[Limit1].[LastName] AS [LastName],
[Limit1].[Email] AS [Email],
[Limit1].[LastPurchaseDate] AS [LastPurchaseDate],
[Limit1].[CreditLimit] AS [CreditLimit],
[Limit1].[Photo] AS [Photo],
[Extent3].[OrderItemId] AS [OrderItemId],
[Extent3].[OrderId] AS [OrderId1],
Search WWH ::




Custom Search