Can I lazy load a navigation property by delegating to a stored procedure in EF?
Asked Answered
C

1

9

I have the following customer class:

public class Customer 
{
    public long Id { get; set; }

    public virtual ICollection<Order> Orders { get; set; }
}

My database has Customers and Orders tables, but no foreign key relationships. Orders for a customer are obtained using a stored procedure that takes the customer ID and returns the order rows. I can't modify the database.

I know how to call the stored procedure from Entity Framework, but, is it possible to configure the DbContext using the fluent API so that accessing the Orders collection of a customer object would lazy load the entities via a call to the stored procedure?

I'm using the latest version of EF.

Candi answered 20/10, 2014 at 14:41 Comment(2)
I'd be very surprised if you could, I think the only options are Eager Loading or creating a foreign key.Katt
Can't you create a view which does the same? Why would you want lazy loading? Why do you need stored procedures?Bureaucratize
O
1

No, you can't. Lazy loading is coded in the proxy object that EF creates (if possible), there's no way to intercept/configure the way proxies are generated.

It's not even possible to map the default read action of a DbSet to a stored procedure. It's always a query. Only create, update and delete can be mapped to stored procedures.

The reason (I think) is that stored procedures are not composable, so if in a complex LINQ query one entity would be mapped to a stored procedure (for reading) it wouldn't be possible to turn the query into one SQL statement.

Orelle answered 3/7, 2015 at 19:50 Comment(1)
based on the answer above, the only option for lazy loading would be to create a view.Mcclendon

© 2022 - 2024 — McMap. All rights reserved.