1

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?

3
  • Could you make the assumption that CustomerId would be zero (default) if the Customer object is not attached? Commented Mar 26, 2012 at 17:19
  • @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). Commented Mar 26, 2012 at 17:39
  • @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. Commented Mar 26, 2012 at 19:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.