Obtain the value of the foreign key in Entity Framework 1.0 without Include method


I'm using VS2008 (.NET 3.5) and Entity Framework over SQL Server. I'm hoping to get the value of a foreign key column without using the Include() method to link up the table.

For example, the simple Author has many Books sample.

var book = context.Books.First();
int authorId = book.Author.AuthorId;

In this scenario, an exception is thrown, because Author is null. I'm looking to just get the author ID, but don't need the rest of the Author object. There is no AuthorId property on the Book class.

I'm sure there's a way to do this, probably by editing the EDMX directly, or maybe through the designer - any ideas how to get started?


You can get the FK value but it is not as straight forward. Each your navigation property representing single entity should have its pair property called XXXReference. In your case AuthorReference. This is the EF infrasturcture property holding your key internally. You can use similar code to get your FK value:

EntityKey key = book.AuthorReference.EntityKey;
EntityKeyMembers[] keyMembers = key.EnityKeyValues;
// Now each member of this array contains Key and Value property. Key is the name of
// primary key property in principal entity and value is its value
// If you don't have composite keys and your keys are integer you can simply use:
int authorId = (int)keyMembers[0].Value;