gpt4 book ai didi

c# - Entity Framework 并向查找表添加引用/条目

转载 作者:行者123 更新时间:2023-11-30 20:56:52 24 4
gpt4 key购买 nike

我有一个项目,我使用查找表将两个表链接在一起:

Day         WeatherLookUp       Weather
--- ------------- -------
ID (PK) --> DayID |- ID (PK)
WeatherID <---| Description

这允许我指定一天的多个天气条件。

我可以毫无问题地阅读它,但我的问题是当我开始在 Day 和 Weather 表之间插入链接时。我创建了 WeatherLookup 表的两列作为表的复合主键,因此 EF 不允许我直接插入到 WeatherLookup 表中。

我以为我只需要像这样添加一个天气条目:

myDay.Weather.Add(new Weather { ID = 2 } );

...但 EF 认为我正在尝试添加新的天气类型。

我确定我遗漏了一些明显的东西,但我不知道是什么,我需要以某种方式使用 Attach() 吗?

最佳答案

您需要将 Weather 实体附加到上下文,以便告诉 EF 它已经存在于数据库中并且不需要插入:

var weather = new Weather { ID = 2 };
context.Weather.Attach(weather);
myDay.Weather.Add(weather);

或者,您可以从数据库加载实体(这会将其隐式附加到上下文):

var weather = context.Weather.Find(2);
myDay.Weather.Add(weather);

关于c# - Entity Framework 并向查找表添加引用/条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17271610/

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