实体框架EntityKey/外键问题
作为表单发布的结果,我正在尝试保存新的品牌记录。 在我看来,性别是一个下拉列表,返回一个整数,它是从 ViewData("gender") 填充的。
我已按如下方式设置链接:
gID = CInt(Request.Form("Gender"))
Brand.GenderReference.EntityKey = New EntityKey("DB_ENTITIES.Gender", "Id", gID)
TryUpdateModel(Brand)
DB.SaveChanges()
这会导致以下错误。
Entities in 'DB_ENTITIES.Brand' participate in the 'FK_Brand_Gender' relationship. 0 related 'Gender' were found. 1 'Gender' is expected.
有人可以用简单的英语向我解释这些参数吗? 我也尝试过 DB.Gender 作为第一个参数,但没有任何乐趣。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个存根 Gender 对象,而不是创建 EntityKey
(抱歉,我不是 VB 人员,所以在 C# 中):
然后将性别附加到相应的 EntitySet(您从中获取性别实体的
DB
上的属性名称)是下面的字符串):这会将数据库置于
ObjectContext
中的 Gender 处于未更改状态的状态,而无需数据库查询。 现在你可以像往常一样建立关系了,就是这样。 无需使用
EntityKeys
希望这会有所帮助
Alex
Rather than creating an EntityKey create a stub Gender object
(sorry I'm not a VB guy so in C#):
Then you attach the Gender to the appropriate
EntitySet
(the name of property onDB
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 normalThat is all there is to it. No need to muck around with
EntityKeys
Hope this helps
Alex
您需要的是 Brand 和 Gender 的实例,然后将 Brand.Gender 设置为 Gender 的实例。 然后你就可以毫无问题地保存了。
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.
好吧,这就是我想出的而不是使用 updateModel 的方法。 无论如何,这似乎是有问题/潜在的安全风险,因为帖子中可能添加了其他字段。 可以通过 trygetObjectByKey 实例化 Gender 的新实例。 到目前为止,这是有效的。 对于让 UpdateModel 更新 Gender 属性对象的任何其他建议,我们表示赞赏。
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.