1

I have a database like the following example:

Customer

CustomerID int
Name...

Document

DocumentID int
CustomerID int
DocumentDate...

Here's the thing. Not all documents are related to a customer. The problem is that this old database doesn't use an int NULL for Document->CustomerID. Instead, it's a nonnullable int, and it uses a stored value of -1 to indicate that it doesn't have a customer. The code that runs on top of this database knows that -1 is special, and indicates no related entity.

My problem is that now I want to build an entity model on top of it. Is there a way to tell the Entity Model that a -1 in the CustomerID field on the Document table means there is no relationship? Entity Framework would have to map the int at the database layer to a nullable int at the model layer, and whenever it retrieved a record from the db, it would have to map the value of -1 to a null, and whenever it saved, save a null as a -1. And when populating entitysets, this mapping would have to be factored in as well.

Does this make sense? It seems like something that Entity Framework might have built in under the covers somewhere, but then again, maybe not.

Ideas?

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
John West
  • 41
  • 2

1 Answers1

0

If database doesn't have relation built on top of these entities (which it cannot have based on your description) EF will not create such relation for you. If you are using EFv4 you can define the relation yourselves as Foreign key association.

EF will handle this as any other relationship. You will have to cheat EF by setting FK to -1 or navigation property to new Customer { Id = -1 } and you will have to ensure that this dummy entity has always state set to Unchanged by calling context.ObjectStateManager.ChangeObjectState. Otherwise EF will try to create or modify this entity when persisting Document.

Separate problem can be lazy loading \ eager loading. I'm really not sure how will EF handle situation when FK contains Id of non existing entity. I'm somehow afraid that both lazy and eager loading will throw exception.

The easiest way to handle these problems is creating special NullCustomer in your database with Id -1 so that you use relation with a real database record.

EF has no support for your scenario.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • "EF has no support for your scenario". That's what I'm afraid of. You've thought of the same things I have. I don't want to go putting dummy records in with id of -1, because that creates all kinds of other issues. Before I mark it as answered, let's see if anyone has any other thoughts on this. I'm still holding out hope that somehow, someway, there's a super hidden way to do this! – John West May 19 '11 at 20:47