我正在编写一个从文件读取数据然后更新数据库的代码(即删除整个数据库并重新填充表格)
我有以下4
var e=document.getElementById("cbostatus");
var strUser = 'Planned'; // get this value from somewhere, maybe a hidden field
if( strUser == 'Planned' ) {
e.options[e.length]=new Option("Planned", "optionPlanned", true, true);
e.options[e.length]=new Option("Started", "Started");
} else if ..
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),
);
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
);
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
);
我正在使用以下代码:
CREATE TABLE Departments (
[Id] INT NOT NULL,
[Name] NVARCHAR (20) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
每当我想要删除整个数据库并用不同的行重新填充数据时,我会得到一些错误的错误,说“无法插入或更新实体,因为'X'关系的主要末端被删除了。”其中X是一些fk约束..
我想我的问题是更新表Courses_Specializations,因为这个表只包含外键,所以我更新这个表的方法是创建1个特化和1个课程,并使用导航属性将它们相互连接
另一个重要注意事项是,当我执行以下操作时
它运作正常..但是当我做的时候
它抛出异常
答案 0 :(得分:4)
要确定问题在哪里尝试在每个ctx.SaveChanges()上设置断点;并调试您的应用程序
ctx.Departments.AddRange(departments);
ctx.SaveChanges();
ctx.Courses.AddRange(courses);
ctx.SaveChanges();
ctx.Specializtions.AddRange(specializations);
ctx.SaveChanges();
找到导致问题的表后,使用foreach循环尝试为每个条目插入和SaveChanges并检查哪个行有问题。