Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 730
dommer Avatar asked Oct 20 '14 14:10

dommer


1 Answers

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.

like image 71
Gert Arnold Avatar answered Oct 07 '22 13:10

Gert Arnold