Xoroles
Xoroles

Reputation: 11

Entity Framework Foreign Keys with Zero Values

I have the following Problem, i must connect a Exiting Database with a very Ugly and not Normalized Design. So I have many ForeignKeys with Not Null but a Foreign Key with Value 0 (Zero) so it was a Null Reference.

But in Some Tables i have also Nullable FKs but also Zero Values.

Can I Customize Entity Framework with Some Convention or something else. So EF knows, if column is Not Null and I Say the Reference is Optional in Fluent it write a Zero in the Not Null Column.

The Only other Solution is to write Views for Read Access, and Sps for Write Access to make a Valid Abstraction on the Databasse. But with more then 500 Tables it was some many Work.

So has somebody a Idea for some better Solution.

A Additional Notice, the database is in Refactoring, so in one or two years it is Normalized, and has not an so Ugly design.

The database System ist MsSql

Sorry for my bad English.

Upvotes: 1

Views: 781

Answers (1)

Ppp
Ppp

Reputation: 1015

So EF knows, if column is Not Null and I Say the Reference is Optional in Fluent it write a Zero in the Not Null Column.

I would write it as this when inserting

myTable.destFK_Field = sourceFK_Field ?? 0

The SQL equivalent:

myTable.destFK_Field = COALESCE(sourceFK_Field,0)

Assuming that you are generating the models from EDMX, I think there is not much option that you can add to the models.

Upvotes: 1

Related Questions