Say I have the following entity classes:
public class Order
{
public int OrderID { get; set; }
public ICollection<OrderLine> OrderLines { get; set; }
}
public class OrderLine
{
public int OrderLineID { get; set; }
public Order Order { get; set; }
}
I want to enforce a minimum cardinality of 1 for this relationship; ie I want to ensure that an Order cannot be created without at least 1 OrderLine.
I’m using EF code first fluent style configurations and I am able to enforce the fact that OrderLine must have an Order reference (using HasRequired() extension method) but I cant see how I can prevent an Order from being created without at least one OrderLine.
In short: you can’t. Your requirement cannot be mapped to a database constraint: orders and order lines are saved separately, so when you create an order and add an order line, either the order or the order line must be saved first. The order line -> order relation is backed by a foreign key, so the order must be saved first. When the order is saved, as far as the database knows, the order has no order lines, they’re not added until later.
You can create custom validation functions and call them before saving. If you’re using an
ObjectContext, you will have to do this yourself. If you have aDbContext, you should be able to overrideDbContext.ValidateEntity. For obvious reasons, this only works if you make all database modifications through your context. If you modify the database tables directly, custom validation functions don’t get used.