简体   繁体   中英

Failed to insert data through LINQ to SQL server

I'm trying to insert data into the database using LINQ. In me SQL server side I wrote a sequence to generate a custom id with a prefix. Here what I did in my code,

ALLibraryDataClassesDataContext dbContext = new ALLibraryDataClassesDataContext();
dbContext.Books.InsertOnSubmit(book);
dbContext.SubmitChanges();
dbContext.Dispose();

In my book object I'm not setting the BookID because it's generating from the sequence. When I'm executing

INSERT INTO library_db.dbo.Book([BookName]) VALUES ('SH')

This inserts data with the auto generated id. But when I'm running the code, It gives an SQLException,

Cannot insert the value NULL into column 'BookId', table 'library_db.dbo.Book'; column does not allow nulls. INSERT fails.

EDITED My sequence and table creation,

CREATE TABLE [dbo].[Book] (
[BookId]          VARCHAR (50)   NOT NULL,
[BookName]        VARCHAR (50)   NULL,
[AuthorName]      VARCHAR (50)   NULL,
[PublisherName]   VARCHAR (50)   NULL,
[PublishedDate]   DATE           NULL,
[price]           MONEY          NULL,
[PurchasedDate]   DATE           NULL,
[PurchasedBillNo] VARCHAR (50)   NULL,
[CategoryId]      VARCHAR (50)   NULL,
[NoOfCopies]      VARCHAR (50)   NULL,
[FinePerDay]      MONEY          NULL,
[BookImage]       VARCHAR (2000) NULL,
PRIMARY KEY CLUSTERED ([BookId] ASC),
CONSTRAINT [FK_Book_Category] FOREIGN KEY ([CategoryId]) REFERENCES [dbo].
[Category] ([CategoryId])
);

GO
CREATE SEQUENCE dbo.BookId_Seq AS
INT START WITH 1
INCREMENT BY 1 ;
GO
ALTER TABLE dbo.Book
ADD CONSTRAINT Const_BookId_Seq
DEFAULT FORMAT((NEXT VALUE FOR dbo.BookId_Seq),'B0000#') FOR [BookId];
GO

What is the different between running a query manually and through LINQ? Is there a possible way to insert data into code(LINQ) with a custom id?

I'm not sure if you can do this with LINQ-to-SQL, but give it a try:

In the context designer, set "Auto Generated Value" = true for BookId . This tells LINQ-to-SQL to exclude the column from insert statements. Now the database will fall back to the default constraint, which doesn't happen when an insert statement supplies a value.

However, there may be one problem. When auto-generated value is defined for a primary key column, LINQ-to-SQL will try to read the generated value afterwards by a select statement looking like

SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]

Obviously, drawing the value from a sequence will leave SCOPE_IDENTITY() undefined. At best this will prevent you from reading the generated key value from the book variable after SubmitChanges , but in the worst case it will cause an error that you can't work around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM