Consider the below Order object as an Entity Framework entity.
If I was to cast an instance of Order down to IOrder, and then access the Lines property on IOrder, would that cause the virtual OrderLines property to enumerate and load all the OrderLine entities from the database, returning a populated collection of OrderLine entities in memory?
Or will the client code just get a reference to the OrderLines collection, which will load the entities from the database once it is actually enumerated such as in a foreach?
public interface IOrder
{
IEnumerable<OrderLine> Lines { get; }
}
public class Order : IOrder
{
public int OrderId { get; set; }
public IEnumerable<OrderLine> Lines
{
get
{
return OrderLines;
}
}
public virtual ICollection<OrderLine> OrderLines { get; set; }
public Order()
{
OrderLines = new List<OrderLine>();
}
}
It will return a reference to the
OrderLinesobject, but exposed asIEnumerable. Which means that only an enumeration in client code will actually enumerate the the collection. This is the entire collection: linq filters (Where) and projections (Select) will not be translated to SQL.Note that this neither of these may be desired. First, the context must be alive to allow lazy loading and second, the collection may be ‘large’ (although with order lines that probably won’t be a point). Depending on the type of application it may be better to transfer a pre-populated OrderDto object to the client.