Using Entity Framework to save data that have foreign key constraints
<p>I'm writing a code that reads data from files and then updates the DB (i.e deletes the entire DB and refill the tables)</p>

<p>I have the following 4</p>

<h3>Courses</h3>

<pre><code>CREATE TABLE Courses (
    [Id]          INT           IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (50) NULL,
    [SubjectCode] INT           NOT NULL,
    CONSTRAINT [PK_Courses] PRIMARY KEY CLUSTERED ([Id] ASC),
);
</code></pre>

<h3>Specializations</h3>

<pre><code>CREATE TABLE Specializtions (
    [Id]    INT           NOT NULL,
    [Name]  NVARCHAR (50) NULL,
    [DepId] INT           NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_Specializtions_To_Departments] FOREIGN KEY ([DepId]) REFERENCES [dbo].[Departments] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE
);
</code></pre>

<h3>Courses_Specializations</h3>

<pre><code>CREATE TABLE Courses_Specializations (
    [CourseId] INT NOT NULL,
    [SpecId]   INT NOT NULL,
    PRIMARY KEY CLUSTERED ([CourseId] ASC, [SpecId] ASC),
    CONSTRAINT [FK_Courses_Specializations_ToSpecializtions] FOREIGN KEY ([SpecId]) REFERENCES [dbo].[Specializtions] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [FK_Courses_Specializations_ToCourses] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Courses] ([Id]) ON DELETE CASCADE
);
</code></pre>

<h3>Departments table</h3>

<pre><code>CREATE TABLE Departments (
    [Id]   INT           NOT NULL,
    [Name] NVARCHAR (20) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
</code></pre>

<p>I'm using the following code:</p>

<pre><code>CoursesEntities ctx = new CoursesEntities();

// create 3 lists with relevant data and enters them to db

ctx.Departments.AddRange(departments);
ctx.Courses.AddRange(courses);
ctx.Specializtions.AddRange(specializations);
ctx.SaveChanges();
</code></pre>

<p>and whenever I want to delete the entire db and refill the data with different lines I get get verious errors saying "Unable to insert or update an entity because the principal end of the 'X' relationship is deleted." where X is some fk constraint..</p>

<p>I guess my problem is updating the table Courses_Specializations because this table contains only foreign keys so the way I update this table is by creating 1 specialization and 1 course and connects them to each other using the navigation properties</p>

<p>another <strong>important</strong> thing to notice is that when I perform the following</p>

<ol>
<li>clean db  </li>
<li>save changes  </li>
<li>refill data  </li>
<li>save changes  </li>
</ol>

<p>it works fine.. but when i do</p>

<ol>
<li>clean db</li>
<li>refill data  </li>
<li>save changes  </li>
</ol>

<p>it throws the exception</p>