开发者

Entity Framework support for old database that uses -1 to indicate no relationship?

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 e开发者_C百科ntity.

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜