2

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.

yesman
  • 7,165
  • 15
  • 52
  • 117

1 Answers1

2

There's no real native way to accomplish this with EF or SQL, i.e. you can't create an A without a B, and you can't create a B without an A. Stalemate.

You'll need to create some logic in your business layer to enforce the constraint. E.g.

class A
{
    ...
    public A(B b)
    {
        this.Bees = new List<B>();
        this.Bees.Add(b);
    }
}

class B
{
    ...
    public B(A a)
    {
        this.MyA = a;
    }
}

N.B. Presuming code-first, if db-first make your customisations in a partial class.

Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
  • Thanks, this was driving me mad. I like to keep my EF poco's as clean as possible, so I'll move that logic out of the DAL and into the Business logic layer. – yesman Feb 18 '16 at 10:28