Problem with Entity Framework EntityKey / Foreign Key

entity entity-framework entitykey foreign-keys


As the result of a form post, I'm trying to save a new Brand record. In my view, Gender is a dropdown, returning an Integer, which is populated from ViewData("gender")

I've setup my link as follows:

gID = CInt(Request.Form("Gender"))
Brand.GenderReference.EntityKey = New EntityKey("DB_ENTITIES.Gender", "Id", gID)

Which results in the following error.

Entities in 'DB_ENTITIES.Brand' participate in the 'FK_Brand_Gender' relationship. 0 related 'Gender' were found. 1 'Gender' is expected.

Could someone explain the parameters in plain english to me. I've also tried DB.Gender as the first parameter but no joy.

6/24/2009 1:56:20 PM

Accepted Answer

Rather than creating an EntityKey create a stub Gender object (sorry I'm not a VB guy so in C#):

Gender g = new Gender{ID = Int32.Parse(Request.Form("Gender"))};

Then you attach the Gender to the appropriate EntitySet (the name of property on DB that you get Gender entities from is the string below):


This puts the database in the state where the Gender is in the ObjectContext in the unchanged state without a database query. Now you can build a relationship as per normal

brand.Gender = g;

That is all there is to it. No need to muck around with EntityKeys

Hope this helps


4/16/2010 5:23:04 AM

Popular Answer

What you need is an instance of both Brand and Gender and then set Brand.Gender to the instance of the Gender. Then you can save without problems.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow