CBlack
CBlack

Reputation: 683

Code First Foreign Key Configuration

I am having difficulty maintaining multiple relationships between a parent class and it's children. Can anyone tell me why I can create two child references in the parent but not a third? The code below only works when the third reference is commented out.

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Child1Id { get; set; }
    public Child Child1 { get; set; }
    public int Child2Id { get; set; }
    public Child Child2 { get; set; }
    //public int Child3Id { get; set; }
    public Child Child3 { get; set; }
    public ICollection<Child> Children { get; set; }
}
public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public Parent Parent { get; set; }
}
public class CFContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>()
            .HasRequired(c => c.Parent)
            .WithRequiredPrincipal(p => p.Child1)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Child>()
         .HasRequired(c => c.Parent)
         .WithRequiredPrincipal(p => p.Child2)
         .WillCascadeOnDelete(false);

        //modelBuilder.Entity<Child>()
        // .HasRequired(c => c.Parent)
        // .WithRequiredPrincipal(p => p.Child3)
        // .WillCascadeOnDelete(false);
    }
}

Upvotes: 0

Views: 839

Answers (1)

bjorncs
bjorncs

Reputation: 1270

It looks like you are trying to make a one-to-many relation from Parent to Child entity. In that case the code should look like this:

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Child> Children { get; set; }
}
public class Child
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public Parent Parent { get; set; }
}

You don't have to specify the relation in Fluent API as long as you are following the default conventions regarding naming of the navigation properties and foreign key. You will have to use Fluent API and/or attributes to configure relations of you use non-convention names, eg renaming ParentId some something else requires you to mark it with at [ForeignKey("Parent")] attribute.

The most common use case for using Fluent API is for disabling cascade delete (there is no way to do this with attributes).

Upvotes: 1

Related Questions