Search code examples
c#sql-serverdatabaseentity-frameworkdb-first

Using Entity Framework to save data that have foreign key constraints


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)

I have the following 4

Courses

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

Specializations

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

Courses_Specializations

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

Departments table

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

I'm using the following 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();

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..

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

another important thing to notice is that when I perform the following

  1. clean db
  2. save changes
  3. refill data
  4. save changes

it works fine.. but when i do

  1. clean db
  2. refill data
  3. save changes

it throws the exception


Solution

  • To be sure where problem is try to put break point on each ctx.SaveChanges(); and debug your application

     ctx.Departments.AddRange(departments);
        ctx.SaveChanges();
        ctx.Courses.AddRange(courses);
        ctx.SaveChanges();
        ctx.Specializtions.AddRange(specializations);
        ctx.SaveChanges();
    

    After locating the table that causes the problems, using a foreach loop try to insert and SaveChanges for each entry and check which line/s had the problem.