2

The following code creates foreign key errors when all code is not commented.

public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int FavoriteChildId { get; set; }
    public Child FavoriteChild { get; set; }
    //public int WorstChildId { get; set; }
    public Child WorstChild { 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; }
}

It works if the foreign key names aren't specified but then there's no way to edit the models. Does anyone know how to specify the foreign key names?

podiluska
  • 50,950
  • 7
  • 98
  • 104
CBlack
  • 683
  • 1
  • 5
  • 9

1 Answers1

3

Following the naming convention will create the proper FK's above - your code:

public int WorstChildId { get; set; }
public Child WorstChild { get; set; }

Does create the FK of WorstChildId for WorstChild. However, when I tried the code you had above, I got a multiple delete path error (Parent -> WorstChild -> ChildTable, Parent -> FavoriteChild -> ChildTable)

You can set either one, or both of your mappings to not cascade on delete, and that will fix your problem:

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.WorstChild)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Child>()
         .HasRequired(c => c.Parent)
         .WithRequiredPrincipal(p => p.FavoriteChild)
         .WillCascadeOnDelete(false);
    }
}
Mark Oreta
  • 10,346
  • 1
  • 33
  • 36
  • Thanks @Mark, your solution worked great for the above example. Unfortunately, I require a 3rd parent-child reference which doesn't seem to work. If you have a moment, please check out my latest question, which contains the problem code. [link](http://stackoverflow.com/questions/12062202/code-first-foreign-key-configuration) – CBlack Aug 21 '12 at 21:11