0

I have a strange problem. I want to insert an item to a table from database. I use Entity Framework. Although the Id is set, I keep getting the following error:

Cannot insert the value NULL into column 'Id', table 'project_atp.dbo.ShoppingCarts'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

enter image description here

The table definition:

CREATE TABLE [dbo].[ShoppingCarts] (
[Id]           INT              NOT NULL,
[Guid]         UNIQUEIDENTIFIER NULL,
[Name]         NVARCHAR (255)   NULL,
[Code]         NVARCHAR (255)   NULL,
[SupplierNo]   NVARCHAR (255)   NULL,
[SupplierName] NVARCHAR (255)   NULL,
[Price]        NVARCHAR (50)    NULL,
[Quantity]     INT              NULL,
CONSTRAINT [PK_ShoppingCarts] PRIMARY KEY CLUSTERED ([Id] ASC)
 );

Can you please advise what could be wrong here! Thanks!

Orsi
  • 545
  • 2
  • 10
  • 27
  • 3
    My first thought is that field mapping is incorrectly defined for the `Id` column, and it subsequently isn't sent. – MBender Mar 24 '17 at 10:11
  • Could you please post your table definitions? – toonice Mar 24 '17 at 10:11
  • I've updated the question with the table definition – Orsi Mar 24 '17 at 10:15
  • I've managed to solve the problem with changing the definition for Id in database, to: CREATE TABLE [dbo].[ShoppingCarts] ( [Id] INT IDENTITY (1, 1) NOT NULL,......... – Orsi Mar 24 '17 at 10:41
  • If you've solved the problem, then feel free to write your own answer to your question, so that if people have a similar problem in the future they might see your own solution. – MBender Mar 24 '17 at 11:31

1 Answers1

1

By default Entity Framework assumes that an integer primary key is database generated. As the result Entity Framework would not include Primary Key field in the actual INSERT statement.

I would try to either play along and ALTER the table to auto-generate the ID (which judging by your comment you did)

or set StoreGeneratedPattern property of OnlineCarStore.Models.ShoppingCarts Id column to 'None'

or use annotation: [DatabaseGenerated(DatabaseGeneratedOption.None)].

Community
  • 1
  • 1
Y.B.
  • 3,526
  • 14
  • 24