Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework - Saving child entities
    primarykey
    data
    text
    <p>I'm using EF and WebAPI and trying to save a new object that has many child properties (eg city, country, etc). The data for these properties is pulled from an external source but I want to save them to my database along with my object for reporting purposes. For that reason I need to first check if the new child being passed along with the new parent already exists (remember, it's not being pulled from my database). </p> <p>If I've selected, for example, a city I've already saved, it saves a duplicate row because the object passed in doesn't have MY city ID so EF thinks it's a new item.</p> <p>I've tried attaching if it is already in the DB but it won't let me attach. It says the item is already being tracked by the context. </p> <p>Here is my code for trying to check and save one of the child collections before saving the new parent.</p> <pre><code>foreach (HBCountry country in hbcampaign.HBTargetingSpec.HBCountries) { if (db.HBCountries.Any(c =&gt; c.country_code == country.country_code)) { country.CountryID = db.HBCountries.Where(c =&gt; c.country_code == country.country_code) .FirstOrDefault() .CountryID; db.HBCountries.Attach(country); } else { db.HBCountries.Add(country); } } </code></pre> <p>I need to grab the ID of the existing entity from my context but after that I can't attach and let EF know that it doesn't need to create a new entry for this item. </p> <p>I'm pretty new to EF and I'm constantly struggling with saving / updating any entities that have child collections. I can't seem to wrap my mind around when things are attached to the context and when not etc. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload