尝试在FK T-SQL上将记录插入表错误

时间:2016-08-16 02:38:48

标签: c# sql-server visual-studio-2015

我正在尝试将新的课本记录插入到数据库中。我有一个Course表,其中包含ID(PK),CourseIDCourseTitle列。

textBook表(所有列,ID(PK))是多对多关系,因此多个课程可以拥有相同的书籍,课程也可以有多本不同的书籍。

当我尝试使用C#将新教科书插入我的数据库时,我的外键出错了。 Course表是父表,Textbook表是子表。两个表中的ID列都设置为标识和自动递增。 ID是引用textBook表的Course表中的外键。

这是我的中间表。

CREATE TABLE [dbo].[BookCourse]
(
[cID] INT NOT NULL Unique, 
[BookID] INT NOT NULL Unique, 
[BookCourseID] INT NOT NULL, 
CONSTRAINT [PK_BookCourse] PRIMARY KEY ([BookCourseID]) 
)

这是我的textBook表

CREATE TABLE [dbo].[textBooks] (
[thirteenISBN]   VARCHAR (255) NOT NULL,
[CourseID]       VARCHAR (50)  NOT NULL,
[BookTitle]      VARCHAR (255) NULL,
[Ancillary]      VARCHAR (255) NULL,
[BookActive]     VARCHAR (20)  NULL,
[ActiveDate]     VARCHAR (50)  NULL,
[InactiveDate]   VARCHAR (50)  NULL,
[Author]         VARCHAR (255) NULL,
[Imprint]        VARCHAR (100) NULL,
[Publisher]      VARCHAR (100) NULL,
[EditionAndDate] VARCHAR (120) NULL,
[tenISBN]        VARCHAR (255) NULL,
[VendorISBN]     INT           NULL,
[ebookAvailable] VARCHAR (50)  NULL,
[eISBN]          VARCHAR (255) NULL,
[Notes]          VARCHAR (255) NULL,
[BookID]             INT           IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_textBooks] PRIMARY KEY CLUSTERED ([BookID] ASC), 
CONSTRAINT [FK_textBooks_ToTable] FOREIGN KEY ([BookID]) REFERENCES [BookCourse]([BookID])
);

这是我的课程表

CREATE TABLE [dbo].[Course] (
[CourseID]    VARCHAR (50)  NOT NULL,
[CourseTitle] VARCHAR (255) NULL,
[cID]          INT           IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED ([cID] ASC), 
CONSTRAINT [FK_Course_ToTable] FOREIGN KEY ([cID]) REFERENCES [BookCourse]([cID]) 
);

带插入的表适配器:

JUTDMSTableAdapters.textBooksTableAdapter bookTableAdapter;
bookTableAdapter = new JUTDMSTableAdapters.textBooksTableAdapter();

JUTDMSTableAdapters.CourseTableAdapter courseTableAdapter;
courseTableAdapter = new JUTDMSTableAdapters.CourseTableAdapter();

courseTableAdapter.Insert( CourseID: txtCourseID.Text, CourseTitle: txtCourseTitle.Text);

bookTableAdapter.Insert( thirteenISBN: txt13ISBN.Text, CourseID: txtCourseID.Text, BookTitle: txtBookTitle.Text, Ancillary: txtAncillary.Text,
            BookActive: txtBookActive.Text, ActiveDate: txtActiveDate.Text, InactiveDate: txtInactiveDate.Text, Author: txtAuthor.Text,
            Imprint: txtImprint.Text, Publisher: txtPublisher.Text, EditionAndDate: txtEditionDate.Text,
            VendorISBN: vendISBN, tenISBN: txt10ISBN.Text, ebookAvailable: txtEBookAvailable.Text, eISBN: txtEISBN.Text, Notes: txtNotes.Text);

我想在我的Course表适配器插件中,我不必添加cID列,因为它是自动增量但我收到此错误:

  

附加信息:INSERT语句与FOREIGN KEY约束“FK_Course_ToTable”冲突。冲突发生在数据库“F:\ HUTDMS V-2.0 \ HUTDMS V-2.0 \ APP_DATA \ HUTDMS.MDF”,表“dbo.BookCourse”,列'cID'。

教科书表中的BookID是自动增量 “课程”表中的cID是自动增量 BookCourse表中的BookCourseID是自动增量。

0 个答案:

没有答案