views:

29

answers:

1

Hi! Im dealing with code first .NET 4 and i'm having trouble with a 1 to 1 relation.

breifing of database: -POccurrence -Id

-POccurrenceRiskAssessment -OccurrenceId

in my class Poccurrence I have a property named RiskAsessment, of the type POccurrenceRiskAssessment. Not all POccurrences have riskassessments, so it needs to be nullable. I tried

modelBuilder.Entity<POccurrence>().HasOptional(item => item.RiskAssessment).HasConstraint((o, r) => r.OccurrenceId == o.Id);

but that gives me

The navigation property 'RiskAssessment' declared on type 'AM.Pris.Classes.POccurrence' has been configured as optional. Based on a declared constraint, the navigation property is required. Either make some dependent key property nullable or configure the navigation as required.

and if i try

modelBuilder.Entity<POccurrence>().HasRequired(item => item.RiskAssessment).HasConstraint((o, r) => r.OccurrenceId == o.Id);

i get

A referential integrity constraint violation occurred: A primary key property that is a part of referential integrity constraint cannot be changed when the dependent object is Unchanged unless it is being set to the association's principal object. The principal object must be tracked and not marked for deletion.

and i have no idea what to do. I even tried to delete the real relation in the DB but nothing seems to make any difference. Any idea? I guess its the first try with HasOptional i'm looking for, but how do i make it nullalbe?

A: 

Have you considered rolling this up into an Table Per Type inheritance scenario where POccurrenceRiskAssessment : POccurrence? That way you only need query POccurrenceRiskAssessment.

Slappy