Before we would jsut return the created object because everything was
loaded.
Somehow I doubt that this is true at all. If you call SaveChanges
EF does not execute a query to load the navigation properties, no matter if you use lazy loading or not. For example:
Suppose you have orders with a navigation reference to a customer and in the database is already a customer with Id = 1. Now you create an order (lazy loading is enabled):
var order = context.Orders.Create();
order.CustomerId = 1;
context.Orders.Add(order);
context.SaveChanges();
bool isCustomerLoaded = context.Entry(order).Reference(o => o.Customer).IsLoaded;
isCustomerLoaded
will be false
- unless the customer 1 is already in the context, but then the property will also be populated without lazy loading ("relationship fixup"). Of course as soon as you access order.Customer
it will be loaded due to lazy loading, but that happens afterwards and has nothing to do with SaveChanges
.
If your code is a good idea or not, depends on the way the returned object is used and what the consumer expects. Generally the closest replacement of lazy loading without lazy loading is explicit loading because both loading strategies perform single queries to load a navigation property. It would mean of course that you have to introduce additional code at consumer side to load the properties whereas with lazy loading "it just works" when you use a property and the query happens behind the scenes in the overloaded property getters of the proxy object. Explicit loading would look like this:
context.Entry(order).Reference(o => o.Customer).Load();
// or for collections
context.Entry(order).Collection(o => o.OrderItems).Load();
You had to call this at the places where you access a navigation property at the first time.
If you know in advance that the object returned from your Create
method will need all navigation properties then you could load them with eager loading the way you proposed. But this is definitely a change in your database access patterns compared to lazy loading: Eager loading will only need a single query to load the whole object graph, but this is a potentially very expensive query with a lot of JOINs in the DB and many data returned. Whereas lazy loading and explicit loading will issue multiple queries, but simpler queries with less data returned. Without considering the model details and doing measurements it is impossible to say what is better.