gpt4 book ai didi

entity-framework - Entity Framework EntityKey/外键问题

转载 作者:行者123 更新时间:2023-12-04 09:44:51 24 4
gpt4 key购买 nike

作为表单发布的结果,我正在尝试保存新的品牌记录。在我看来,性别是一个下拉列表,返回一个整数,它是从 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 作为第一个参数,但没有任何乐趣。

最佳答案

而不是创建一个 EntityKey 创建一个 stub Gender 对象
(对不起,我不是 VB 的人,所以在 C# 中):

Gender g = new Gender{ID = Int32.Parse(Request.Form("Gender"))};

然后将性别附加到适当的 EntitySet (您从中获取性别实体的 DB 上的属性名称是以下字符串):
DB.AttachTo("Genders",g);

这会将数据库置于性别在 ObjectContext 中的状态。在没有数据库查询的情况下处于未更改状态。现在你可以正常建立关系了
brand.Gender = g;
DB.AddToBrand(brand);
DB.SaveChanges();

这就是它的全部内容。无需与 EntityKeys 混在一起

希望这可以帮助

Alex

关于entity-framework - Entity Framework EntityKey/外键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1011519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com