Cannot insert the value NULL into column 'Id' although Id is set - sql

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."}
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!

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

Related

The model already has an element that has the same name - ASP.NET

I'm working with ASP.Net web application and whenever I tried to add a FOREIGN KEY this error appears in the Data tools operations :
SQL71508 :: The model already has an element that has the same name
dbo.FK_Sellers_Users. SQL71508 :: The model already has an element
that has the same name dbo.FK_Sellers_Users.
I don't understand what's the problem with FK! I have 2 tables with this error
table Sellers :
CREATE TABLE [dbo].[Sellers] (
[Seller_ID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[SUsername] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[SEmail] NVARCHAR (50) NOT NULL,
[Phone] NVARCHAR (50) NOT NULL,
[City] NVARCHAR (50) NOT NULL,
[LastLoginDate] DATETIME NULL,
[CreatedDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([Seller_ID] ASC),
CONSTRAINT [FK_Sellers_Users] FOREIGN KEY ([SEmail]) REFERENCES [Users]([Email]),
CONSTRAINT [FK_Sellers_Users] FOREIGN KEY ([SUsername]) REFERENCES [Users]([Username])
);
and table Users :
CREATE TABLE [dbo].[Users] (
[Id] INT NOT NULL IDENTITY,
[Username] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (50) NOT NULL,
[Email] NVARCHAR (50) NOT NULL,
[UserType] INT NULL,
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [AK_Users_Username] UNIQUE ([Username]),
CONSTRAINT [AK_Users_Email] UNIQUE ([Email]),
);
Right there in your CREATE TABLE statement for dbo.Sellers, you have two FK constraints named FK_Sellers_Users.
Make those names unique, perhaps by adding the column name on the end.
You have two foreign keys with the same name FK_Sellers_Users. You should better use FK_Sellers_Users_Email and FK_Sellers_Users_Username.
Actually, this has to do with data that was already entered. Some of the PK and FK data that were entered before might have the same values. You need to delete those first and make the changes you need.
If your project uses SSDT (SQL Server Data Tools), you probably have a foreign key defined in a folder for Keys. Look in "DB Name\Schema Objects\Schemas\dbo\Tables\Keys."
Then Look in the table definition. "DB Name\Schema Objects\Schemas\dbo\Tables". The key could be defined in BOTH places.

an error occured while the batch was being executed

I'm trying to make a simple table in a database.
CREATE TABLE [dbo].[klanten]
(
[Klant_naam] TEXT NOT NULL PRIMARY KEY,
[Klant_adres] TEXT NULL,
[klant_gsm] TEXT NULL,
[klant_gewicht] INT NOT NULL,
[klant_lengte] INT NOT NULL,
[klant_klacht] TEXT NOT NULL
)
When I try to update it, the following error pops-up.
As the documentation warns:
ntext , text, and image data types will be removed in a future version
of Microsoft SQL Server. Avoid using these data types in new
development work, and plan to modify applications that currently use
them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
So, try this instead:
CREATE TABLE [dbo].[klanten] (
[Klant_naam] varchar(max) NOT NULL PRIMARY KEY,
[Klant_adres] varchar(max) NULL,
[klant_gsm] varchar(max) NULL,
[klant_gewicht] INT NOT NULL,
[klant_lengte] INT NOT NULL,
[klant_klacht] varchar(max) NOT NULL
)
Well, this doesn't quite work either, because there is a limit of 900 bytes for index keys. How about using a surrogate key and reasonable column lengths?
CREATE TABLE [dbo].[klanten] (
Klant_Id int not null identity(1, 1) primary key,
[Klant_naam] varchar(255) NOT NULL unique,
[Klant_adres] varchar(max) NULL,
[klant_gsm] varchar(max) NULL,
[klant_gewicht] INT NOT NULL,
[klant_lengte] INT NOT NULL,
[klant_klacht] varchar(max) NOT NULL
);
Try to change "TEXT" data type to "NCHAR()" or any other similar to this.
This error usually occured when you try to update database, but some fields can't be updated. For example, I have 5 fields in a table:
[Id] INT IDENTITY (1, 1) NOT NULL,
[Path] NVARCHAR (MAX) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Url] NVARCHAR (MAX) NULL,
[SecureUrl] NVARCHAR (MAX) NULL
I've worked for some time with it, and make some records. And some of them have value NULL at [Url]. Suddenly I decide to change table:
[Id] INT IDENTITY (1, 1) NOT NULL,
[Path] NVARCHAR (MAX) NOT NULL,
[Name] NVARCHAR (50) NULL,
[Url] NVARCHAR (MAX) NOT NULL, //!!! HERE A PROBLEM, I ALREADY HAVE NULL RECORDS IN DATA
[SecureUrl] NVARCHAR (MAX) NULL
Problem is that my data has been made with the old model and it has records with the NULL at [Url], but in new model NULL value can't be at [Url]. So as with new model, old data can't be correct. Thus we have the error when update.

SQL on Azure - using a computed column as a primary key index

I am not sure what is wrong with the below SQL.
I used to have a primary key based off of the customer_reference_no.
They now have some duplicates so I am creating a column called uniquePoint that is a combination of customer_no, customer_reference_no and stop_zip.
The below works fine:
CREATE TABLE [dbo].[stop_address_details] (
[customer_no] NCHAR (5) NOT NULL,
[customer_reference_no] VARCHAR (20) NOT NULL,
[stop_name] VARCHAR (40) NOT NULL,
[stop_address] VARCHAR (40) NULL,
[stop_city] VARCHAR (30) NULL,
[stop_state] CHAR (2) NULL,
[stop_zip] VARCHAR (10) NULL,
[point_no] VARCHAR (20) NULL,
[branch_id] VARCHAR (6) NULL,
[delivery_route] VARCHAR (10) NULL,
[dateTimeCreated] DATETIME NULL,
[dateTimeUpdated] DATETIME NULL,
[estimated_delivery_time] TIME (0) NULL,
[est_del_time] DATETIME NULL,
[dateTimeLastUsedInDatatrac] DATETIME NULL,
[uniquePoint] as customer_no + '_' + customer_reference_no + '_' + stop_zip PERSISTED ,
CONSTRAINT [AK_stop_address_details_customer_reference_no] UNIQUE NONCLUSTERED ([customer_reference_no] ASC),
CONSTRAINT [PK_stop_address_details] PRIMARY KEY ([uniquePoint])
But when I remove the constraint for customer_reference_no I get the following error:
SQL71516 :: The referenced table '[dbo].[stop_address_details]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
I am referencing the computed column and it is persisted.
Not sure what is missing?
Thank you,
Joe
The answer appears to be that I have another table that is referencing this table with a foreign key:
REATE TABLE [dbo].[rep_assigned_stop_matrix] (
[customer_reference_no] VARCHAR (20) NOT NULL,
[rep_id] INT NULL,
[dateTimeCreated] DATETIME NULL,
[sendSMS] BIT NULL,
[sendEmail] BIT NULL,
[id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_rep_assigned_stop_matrix] PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [AK_rep_assigned_stop_matrix_Column] UNIQUE NONCLUSTERED ([customer_reference_no] ASC, [rep_id] ASC),
CONSTRAINT [FK_pod_update_lookup_rep_info] FOREIGN KEY ([rep_id]) REFERENCES [dbo].[rep_info] ([id]) ON DELETE CASCADE,
CONSTRAINT [FK_lookup_Stop_Details] FOREIGN KEY ([customer_reference_no]) REFERENCES [dbo].[stop_address_details] ([customer_reference_no])
);
When this bottom constrain was removed the error went away. What I don't understand is why the error message was not a bit clearer (meaning naming the rep_assigned_stop_matrix table) -- or am I still missing something?
Joe
It seems that your '[dbo].[stop_address_details]' is still referring to the customer_reference_no column. Try Remove and re-add it using the new column name.

Making one of my columns default the DateCreated to current time

I have the following SQL definition:
CREATE TABLE [dbo].[James] (
[JamesID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (255) NOT NULL,
[DateCreated] DATETIME NULL,
CONSTRAINT [PK_dbo.James] PRIMARY KEY CLUSTERED ([JamesID] ASC)
);
How might I make it so new entries have the DateCreated filled out automatically when I create new entries.
What about existing data that has not had that column filled out?
If you are starting from scratch and assuming this is SQL Server:
CREATE TABLE [dbo].[James] (
[JamesID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (255) NOT NULL,
[DateCreated] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT [PK_dbo.James] PRIMARY KEY CLUSTERED ([JamesID] ASC)
);
If you want to update the table you can use this:
ALTER TABLE dbo.James
ADD CONSTRAINT DF_namehere DEFAULT CURRENT_TIMESTAMP FOR DateCreated;
However, any current NULL values will remain NULL with the ALTER TABLE solution. How you want to address this depends if you want to backfill information.

Unique Constraint in Visual Studio SQL Designer

I was looking at ways to make a newly added column a Unique but not primary column. I had a look at this W3School link. But Instead of following their approach I simply changed my table in the Visual Studio designer as.
CREATE TABLE [dbo].[Userpro] (
[Id] INT NOT NULL IDENTITY,
[Name] NVARCHAR (50) NULL,
[Postcode] NVARCHAR (4) NULL,
[Gender] INT NULL,
[Blog] NVARCHAR (MAX) NULL,
[FeedBack] NVARCHAR (MAX) NULL,
[Username] NVARCHAR (50) NOT NULL Unique,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Notice that I simply added "Unique" [Username] NVARCHAR (50) NOT NULL Unique. I am unsure if this has the same effect or should I go back and just use the script in the link.
That is perfect.
Adding UNIQUE will have the effect you describe. It is also explained in the link you provide.