簡體   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