繁体   English   中英

实体框架并向查找表添加引用/条目

[英]Entity Framework and adding a reference / entry to a lookup table

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

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

您不仅需要使用ID,还需要将“天气”与“ WeatherLookUp”相关联。

像这样的东西:

Weather weather = new Weather();
weather.Description = "hi";


WeatherLookUp lookup = new WeatherLookUp ();
lookup.Weather = weather;

myDay.Weather.add(Weather);
myDay.WeatherLookUp.add(lookup);
myDay.SaveChanges();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM