简体   繁体   中英

Entity Framework and adding a reference / entry to a lookup table

I have a project where I use a lookup table to link two tables together:

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

This allows me to specify multiple weather conditions for a day.

I can read from this without any issues but my problem is when I come to insert a link between the Day and the Weather table. I created the WeatherLookup table's two columns as the compound primary key of the table and as a result EF doesn't allow me to do a direct insert into the WeatherLookup table.

I had thought I just needed to add a Weather entry like this:

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

...but EF thinks I'm trying to add a new weather type.

I'm sure I'm missing something obvious but I can't work out what, do I need to be using Attach() in some way?

You need to attach the Weather entity to the context in order to tell EF that it already exists in the database and doesn't need to be inserted:

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

Alternatively you can load the entity from the database (which will attach it implicitly to the context):

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

You need to assiociate the "Weather" with the "WeatherLookUp" not only using the ID.

something like this:

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


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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