Setting Entity Key for a view

When you import a database view using Entity Data Model wizard,you will get an entity that has the same number of columns and data type as the view does.Suppose I have the following view in my database.

image

When I import the view I get the following entity on my model.

image

If you look at the above entity carefully, you would notice EF has marked CustomerId,FirstName,LastName and FullName as the entity key. The entity key EF determines is not random. EF marks all the non null columns as entity key. There are two problems with this approach. First making all non null columns as entity key would increase the entity key size in the ObjectContext and also identity resolution would take longer as compared to have just one property marked as entity key. This is the same problem that you would see in the database when you mark several column as primary key. The clustered index gets big and also you may see performance implications.

So what if you want to change the key to something else. Like in my case, I know the key for this view should be CustomerId. Well in prior version, you had to open the edmx file in xml and change the key manually in the storage layer. However if you update the model from the database, you would loose those changes. In EF4, you can change the key from the model directly and the designer will sync the keys on the storage layer and you would not loose changes when you update the model from the database. In the case above, right click FirstName and uncheck entity key option. Do the same for LastName and FullName. To confirm the changes has been synced in the SSDL layer, open up the model browser and expand the storage section. Figure below show the model browser with both conceptual layer and SSDL layer having CustomerId as the entity key.

image

No Comments