views:

84

answers:

2

I have the following table structure that Entity Framework is correctly returning as a one-to-many:

Patient
{
   PatientId PK
}

Death
{
   DeathId PK
   PatientId FK
}

Unfortunately this DB design is wrong as you can only have one Death per Patient. The design should of been like this instead:

Death
{
   PatientId PK
}

However, this is a production system and the DB is not able to be changed. I am writing a new ASP.Net MVC front-end, so I'm rewriting the DAL layer using Entity Framework.

When I call Patient.Death, I get a collection of Death. I only want it to return me a single or null Death (as the Patient may not yet be dead).

So, I went wading into the Model and tried to change the End2 Multiplicity of the assocation to: 0..1 (Zero or One of Death), but when I build the project I get the error:

Multiplicity is not valid in Role 'Death' in relationship 'RefDeath23'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *.

Can anyone tell me how, if possible, I can force this to be a zero or one association?

+1  A: 

Can you make the EF do what you want? Sure; just lie to the EF about your DB metadata. You can do this by generating your DB against a "correctly" designed DB or by manually editing the SSDL.

However, think twice before you do this.

The EF makes this difficult, I suspect, for a very good reason: Your DB, for worse or better, allows this. By creating a model which doesn't, you would be setting yourself up for a runtime error should you ever encounter this data condition in the wild, because there would be no way to load it into your model. You would be unable to work with such a person at all until you (externally) fixed the bad data in the DB.

Craig Stuntz
+1  A: 

Your EF model should match your database. So if the database is wrong, then the EF model should also be "wrong".

What you can do is to implement this restriction in the business layer.

Shiraz Bhaiji