1
votes

Say you have two classes, order and customer:

public class Customer{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public ICollection<Order> Orders { get; set; }
}

public class Order{
    public int OrderId{get; set;}
    public Customer OrderCustomer{get; set;}
}

Now, I would like to add a "CanBeDeleted" method to my Customer class that tells my program if this customer can be deleted. I want to make sure that a customer can only be deleted if no orders exist:

public class Customer{
       public int CustomerId { get; set; }
       public string CustomerName { get; set; }
       public ICollection<Order> Orders { get; set; }

       [NotMapped]
       public bool CanBeDeleted {
           get {
               return Orders.Count() == 0;
           }
       }
   }

Of course, the problem is, that the program doesn't know if the Customer was loaded with the include option for orders.

How can I make sure from within the "CanBeDeleted" getter that the orders are loaded / how can I load them without having a reference to the DbContext?

1
Could you make the assumption that CustomerId would be zero (default) if the Customer object is not attached? - devuxer
@DamM: If the customer is not attached, Order.OrderCustomer is null (unless this is a new customer that has never been saved to the database, in which case by convention Customer.CustomerId will be 0). - Eric J.
@Eric-J, ahh true. I've gotten into the habit of initializing collections in the constructor so I don't have to check for null. - devuxer

1 Answers

1
votes

By default, Entity Framework Code First will lazy load related entities when they are accessed.

However, your properties that hold the related entities must be declared virtual, which you don't seem to be doing.

The reason they must be declared virtual is that Entity Framework creates a proxy class that overrides your implementation and injects the code to load the related entities upon first access.

http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx