实体框架EntityKey/外键问题 [英] Entity Framework EntityKey / Foreign Key problem

查看:39
本文介绍了实体框架EntityKey/外键问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于表单发布的结果,我正在尝试保存新的品牌记录.在我看来,Gender 是一个下拉列表,返回一个 Integer,它由 ViewData("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")

我的链接设置如下:

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 作为第一个参数,但没有任何乐趣.

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

推荐答案

与其创建EntityKey不如创建stub Gender对象(对不起,我不是 C# 中的 VB 人):

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"))};

然后您将 Gender 附加到适当的 EntitySet(您从中获取 Gender 实体的 DB 上的属性名称是下面的字符串):

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);

这会将数据库置于 Gender 处于 ObjectContext 中的状态,并处于未进行数据库查询的状态.现在你可以正常建立关系了

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();

这就是它的全部内容.无需使用 EntityKeys

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

希望对你有帮助

亚历克斯

这篇关于实体框架EntityKey/外键问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆