After adding a couple of Views to my Entity Data Model, I noticed that EF had messed up the Primary keys of my entities (based on the views). It was picking a lot of fields as Primary, even when they are not Primary. Obvious solution was to manually do what EF should have done for me. So I went ahead and fixed the keys in the Model.
Lo and Behold! I was greeted with an error that all key properties of the entity set must be assigned to all key properties of the table.... WTF?
Oh! Ok... I know EF maps the Store with the Model. I have fixed the Model... but not the Store yet.
To my surprise, you can not edit the store from the designer. Never mind, its just XML, I can edit it using any text editor. So I went ahead and edited the .EDMX XML. I deleted all the incorrect Key entries. For example, I changed this:
<Key>
<PropertyRef Name="HouseID" />
<PropertyRef Name="State" />
<PropertyRef Name="OtherCrapKey" />
</Key>
to this:
<Key>
<PropertyRef Name="HouseID" />
</Key>
This fixed the problem... but only for a while. I knew that every time I change the schema (add / delete / modify a view for my Model), I'd have to "Update Model from Database", that'll again screw up the entire Store.
Googling the issue led to the following post:
So I knew the issue was Non-Nullable fields in the views. And the work around was simple. I made all the non-primary fields as Nullable. For example, if you have the following select statement in the view:
Select idKey, fkidHouseType, 'Vic' State
From tblHouse
This creates all the three fields as Primary in the EF Store (Even when only idKey should be Primary).
Changing it to the following fixes the issue:
Select idKey, Cast(fkidHouseType As Int) fkidHouseType, CAST('Vic' AS VARCHAR(3)) State
From tblHouse
I know it's a work around, but for now, I don't have to manually change the EDMX XML every time I update the schema.
Let me know if you find a better solution or a more efficient way of specifying Nullable values in a View.
Read more!
