实体框架EntityKey /外键问题 [英] Entity Framework EntityKey / Foreign Key problem
问题描述
我设置了我的链接如下:
gID = CInt(Request.Form(Gender))
Brand.GenderReference.EntityKey = New EntityKey(DB_ENTITIES性别,Id,gID)
TryUpdateModel(品牌)
DB.SaveChanges()
其中导致以下错误。
DB_ENTITIES.Brand中的实体参与FK_Brand_Gender关系。发现0相关的性别。 1性别是预期的。
有人可以用简单的英语解释我的参数。我也试过DB.Gender作为第一个参数,但没有喜悦。
而不是创建EntityKey创建一个stub Gender对象
(对不起,我不是一个VB的家伙C#):
性别g = new Gender {ID = Int32.Parse(Request.Form(Gender))};
然后,将Gender附加到相应的 EntitySet
( DB
的属性名称,您所获得的性别实体来自以下字符串):
DB.AttachTo( 性别,克);
这将使数据库处于Gender位于 ObjectContext
在没有数据库查询的不变状态下。现在你可以建立一个正常的关系
brand.Gender = g;
DB.AddToBrand(品牌);
DB.SaveChanges();
这就是它的一切。不需要使用 EntityKeys
希望这有助于
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.
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
这篇关于实体框架EntityKey /外键问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!