Reputation: 1349
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
Upvotes: 2
Views: 624
Reputation: 9314
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.
Upvotes: 0
Reputation: 1349
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.
Upvotes: 3