Entity Framework EntityKey / Foreign Key problem
Solution 1
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):
DB.AttachTo("Genders",g);
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;
DB.AddToBrand(brand);
DB.SaveChanges();
That is all there is to it. No need to muck around with EntityKeys
Hope this helps
Solution 2
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.
Squiggs.
Updated on June 04, 2022Comments
-
Squiggs. almost 2 years
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) TryUpdateModel(Brand) DB.SaveChanges()
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.
-
Squiggs. almost 15 yearsDoes that not involve a round trip to my DB? Surely the View is posting back an ID that can be tied up.
-
Squiggs. almost 15 yearsThanks for the response Alex - getting this now: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
-
Jonathan van de Veen almost 15 yearsIt depends, if the objects are already in the context, it does not require a trip to the db. Alex James code is good to use (it pretty much does as I wrote).
-
Picflight about 14 yearsPaul, how did you solve the 'multiple objects with the same key' issue? I am getting the same.
-
Alex James about 14 yearsBefore attaching something to the context you should check the ObjectStateManager using LINQ to Objects to check that the same object isn't already there.