2

I want to create following table based on below class dictionary. I get exception when I add records. What's wrong with this mapping? This code works if I point Child property of class "B" to another class (example "C").

database table 
    table A {id, name}
    table B {parentId, childId, Type}

Class and Mapping

Public class A
{
   public int Id {get;set;}
   public string Description {get;set;}
}

Public class B
{
   [Key, Column(Order=0)]
   public int ParentId {get;set;}
   [Foreignkey("ParentId")]
   public A Parent {get;set;}

   [Key, Column(Order=1)]
   public int ChildId {get;set;}
   [Foreignkey("ChildId")]
   public A Child {get;set;}

   [Key, Column(Order=2)]
   public string Type {get;set;}

}

UPDATE

Error Message is: Introducing FOREIGN KEY constraint 'B_Parent' on table 'B' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

Thanks,

Ashraf

ashraf
  • 1,319
  • 2
  • 16
  • 24
  • I don't see anything wrong with this mapping. Can you provide info how the code looks like which throws the exception and what's exactly the exception message? – Slauma Oct 18 '11 at 23:03
  • @ Slauma and Ladislav, updated the error message – ashraf Oct 19 '11 at 16:34

2 Answers2

3

After reading the following posts I found the solution. http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations.aspx

Entity Framework Code First - Defining Relationships/Keys

It's the SQL Server error. Class 'A' referencing twice in class 'B'. Code First attempt to turn on cascade delete for both Parent and Child columns in class 'B' which cause the exception.

Fix is manually override one of the cascade option to false in class B. I don't know how to set CascadeOnDelete option as dictionary attribute. But here is the fluent api.

 HasRequired(x => x.Parent)
         .WithMany()
         .HasForeignKey(x => x.ParentId)
         .WillCascadeOnDelete(false);

I wish EF team attempt to write a comprehensive guide for Code First configuration (Fluent API) manual for us. AdventureWorks-2008 database is a great candidate for that.

Community
  • 1
  • 1
ashraf
  • 1,319
  • 2
  • 16
  • 24
  • Ah, good finding! There is indeed no attribute for CascadeOnDelete. It's only possible to configure this in Fluent API. – Slauma Oct 19 '11 at 16:34
0

this exception is SQL server specific.It will go away if you turn off the cascade for the relationship.By default Ef will turn it on for you.you can do this through fluent api. In the relationship just add the following configuration

.WillCascadeOnDelete(false);

hope this helps.

ashutosh raina
  • 9,228
  • 12
  • 44
  • 80
  • i asked a similar question and got a detailed response earlier on SO http://stackoverflow.com/questions/7216595/ef-code-first-giving-problems-in-foreign-keys – ashutosh raina Oct 19 '11 at 16:42