Bye
Bye

Reputation: 2806

Having a difficulty with EF Fluent API

I have 4 tables that like thus:

public class Table1
{
 public int Id {get;set;}
 public string Name {get;set;}
}

public class Table2
{
 public int Id {get;set;}
 public string Name {get;set;}
 public int Table1Id {get;set;}
 public virtual Table1 {get; set;}
}

public class Table3
{
 public int Id {get;set;}
 public string Name {get;set;}
 public int Table2Id {get;set;}
 public virtual Table2 {get; set;}
}

public class Table4
{
 public int Id {get;set;}
 public string Name {get;set;}
 public int Table3Id {get;set;}
 public virtual Table3 {get; set;}
}

And my fluent API is like thus:

modelBuilder.Entity<Table2>().HasRequired(x => x.Table1).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Table3>().HasRequired(x => x.Table2).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Table4>().HasRequired(x => x.Table3).WithMany().WillCascadeOnDelete(false);

When I try to seed the tables, I get this error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Table4_Table3_Table3Id. The conflict occurred in database MyDb, table "dbo.Table3", column 'Id'.The statement has been terminated."

I cannot see where I am going wrong

Upvotes: 0

Views: 207

Answers (1)

NSGaga
NSGaga

Reputation: 14302

do this...

modelBuilder.Entity<Table2>()
    .HasRequired(t => t.Table1)
    .WithMany() // t => t.AllTable2s)
    .HasForeignKey(t => t.Table1ID);

...and above all make it compile ! :) (e.g. public virtual Table1 {get; set;} into public virtual Table1 Table1 {get; set;}

Upvotes: 1

Related Questions