I have two classes, with a 1 - 1..* relationship.
class A
{
public long Id;
public virtual ICollection<B> Bees;
}
class B
{
public long Id;
public A MyA;
}
Now, I'm trying to get my database to behave so that any instance of A has to have at least one B in its ICollection, with no upper limit. Any row of B should have a foreign key reference to an A row. My mapping looks like this:
public AMapping()
{
this.ToTable("A");
this.HasKey(x => x.Id);
}
public BMapping()
{
this.ToTable("B");
this.HasKey(x => x.Id);
this.HasRequired(x => x.MyA)
.WithMany(x => x.Bees);
}
The expected behavior when I do this:
var aaaaah = new A();
aaaaah.Bees = null;
MyDbContext.A.Add(a);
Should be an exception being thrown. But Entity Framework inserts with no complaints. What did I do wrong in my mapping?
Edit: I have made an ugly temporary solution to the problem by putting a [System.ComponentModel.DataAnnotations.Required] annotation over the Bees property. But this only checks if Bees is null or not, not if it's an empty list if it is instantiated.