Problem with self-referential foreign keys with DbContext

Discussion of open issues, suggestions and bugs regarding Entity Framework support in ADO.NET Data providers
Post Reply
magnus
Posts: 11
Joined: Mon 22 Aug 2011 11:07

Problem with self-referential foreign keys with DbContext

Post by magnus » 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:

Code: Select all

            modelBuilder.Entity()
                .HasOptional(p => p.Foo1)
                    .WithMany(c => c.Foos)
                .HasForeignKey(p => new { p.FooId })
                    .WillCascadeOnDelete(false);
When you try to use the DbContext it will 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�.
I think the generated code is wrong. As far as I can tell the HasForeignKey line should say:

Code: Select all

.HasForeignKey(p => new { p.FooReferenceId })

StanislavK
Devart Team
Posts: 1710
Joined: Thu 03 Dec 2009 10:48

Post by StanislavK » Wed 24 Aug 2011 16:08

Thank you for the report, we have reproduced the problem. We will fix it and post here when the corresponding build is available.

As a temporary workaround, you can change the DbContext code generation template: find the line

Code: Select all

foreach(EntityProperty prop in navProperty.Properties) {
and replace it with

Code: Select all

foreach(EntityProperty prop in navProperty.OppositeRelationProperty.Properties) {

Post Reply