Entity Framework EntityKey / Foreign Key problem

自古美人都是妖i 提交于 2019-11-28 10:13:51

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

Alex

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.

Ok heres what I've come up with instead of using updateModel. It appears to be problematic / potentially a security risk anyway with potentially additional fields being added in the post. A New instance of Gender can be instantiated via trygetObjectByKey. This is working so far. Any other suggestions on getting UpdateModel to update the Gender property object appreciated.

Dim cID As Integer
cID = CInt(Request.Form("Gender"))
Dim key As New EntityKey(DB.DefaultContainerName() & ".Gender", "ID", cID)

Dim objGenderDS As New Gender
'Bring back the Gender object.
If DB.TryGetObjectByKey(key, objGenderDS) Then
Brand.GenderReference.EntityKey = key
Brand.Gender = objGenderDS
DB.AddToBrand(Brand)
DB.SaveChanges()
Else
End If
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!