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?
CustomerIdwould be zero (default) if theCustomerobject is not attached?Order.OrderCustomeris 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).