Problem with self-referential foreign keys with DbContext
Posted: Mon 22 Aug 2011 12:10
I think there's a problem with self-referential foreign keys in the DbContext template when using fluent mapping. Suppose you have a model Foo with the PK FooId, and a nullable foreign key FooReferenceId, which references FooId. The DbContext template then generates this code for the association:
When you try to use the DbContext it will say:
Code: Select all
modelBuilder.Entity()
.HasOptional(p => p.Foo1)
.WithMany(c => c.Foos)
.HasForeignKey(p => new { p.FooId })
.WillCascadeOnDelete(false);
I think the generated code is wrong. As far as I can tell the HasForeignKey line should say:One or more validation errors were detected during model generation:
System.Data.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'Foo_Foo1_Target' in relationship 'Foo_Foo1'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Foo_Foo1_Source' in relationship 'Foo_Foo1'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be �1�.
Code: Select all
.HasForeignKey(p => new { p.FooReferenceId })