SQL Script Invalid Column name - sql

BEGIN TRANSACTION
BEGIN TRY
DECLARE #tblRCatOmitTemp TABLE (ID INT IDENTITY(1,1),
RCatId int NOT NULL,
CountryId int NOT NULL)
INSERT INTO #tblRCatOmitTemp
SELECT RCatId, CountryId
FROM dbo.tblRCatOmit TABLOCKX
DROP TABLE dbo.tblRCatOmit
CREATE TABLE dbo.tblRCatOmit(
ID INT IDENTITY(1,1),
RCatId INT NOT NULL,
CountryId INT NOT NULL) ON [PRIMARY]
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT PK_RCatOmit PRIMARY KEY CLUSTERED (ID);
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT FK_RCatOmit_rcatId FOREIGN KEY (RCatId)
REFERENCES dbo.tblRCat (RCatID);
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT FK_RCatOmit_countryId FOREIGN KEY (CountryId)
REFERENCES dbo.tblCountry (CountryID)
SET IDENTITY_INSERT dbo.tblRCatOmit ON
INSERT INTO
dbo.tblRCatOmit(
ID,
RCatID,
CountryID)
SELECT
ID,
RCatID,
CountryID
FROM
#tblRCatOmitTemp
SET IDENTITY_INSERT dbo.tblRCatOmit OFF
COMMIT TRANSACTION tblRCatOmit;
END TRY
BEGIN CATCH
PRINT N'Something Happend!'
ROLLBACK;
END CATCH
I have to add a new IDENTITY field as well as PKs and FKs's to a table. I'm trying to save the data into a temp table, drop the original table and then recreate it.
When I run this script I get an error:
Invalid column name 'ID'
I'm guessing it is doing a pre-compile and letting me know that ID doesn't exist in the current table.
What do I need to do to modify this script so it runs?
When I double click the Invalid column name 'ID' message it brings me to this part of the script:
INSERT INTO
dbo.tblRCatOmit(ID,
RCatID,
CountryID)

BEGIN TRANSACTION
BEGIN TRY
IF OBJECT_ID('tempdb..#tblRCatOmitTemp') IS NOT NULL
BEGIN
DROP TABLE #tblRCatOmitTemp
END
CREATE TABLE #tblRCatOmitTemp (
RCatId int NOT NULL,
CountryId int NOT NULL)
INSERT INTO #tblRCatOmitTemp
SELECT RCatId, CountryId
FROM dbo.tblRCatOmit TABLOCKX
DROP TABLE dbo.tblRCatOmit
CREATE TABLE dbo.tblRCatOmit(
ID INT IDENTITY(1,1),
RCatId INT NOT NULL,
CountryId INT NOT NULL) ON [PRIMARY]
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT PK_RCatOmit PRIMARY KEY CLUSTERED (ID);
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT FK_RCatOmit_rcatId FOREIGN KEY (RCatId)
REFERENCES dbo.tblRCat (RCatID);
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT FK_RCatOmit_countryId FOREIGN KEY (CountryId)
REFERENCES dbo.tblCountry (CountryID)
INSERT INTO
dbo.tblRCatOmit(
RCatID,
CountryID)
SELECT
RCatID,
CountryID
FROM
#tblRCatOmitTemp
COMMIT TRANSACTION tblRCatOmit;
END TRY
BEGIN CATCH
PRINT N'Something Happend!'
ROLLBACK;
END CATCH
If you have any amount of data at all use a Temp Table not a table variable, because performance will be a lot better!
Next don't build the ID on the temp table it is arbitrary if you do that and on your insert back to your newly recreated table it will build it there for you. Also means no need to set identity insert on.
If you don't want to use a temp table and add that insert you could also use sp_rename to rename your existing table....
And if you don't care about ordinal position of the columns then simply add the column and then the keys.
ALTER TABLE dbo.tblRCatOmit
ADD ID INT IDENTITY(1,1)
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT PK_RCatOmit PRIMARY KEY CLUSTERED (ID);
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT FK_RCatOmit_rcatId FOREIGN KEY (RCatId)
REFERENCES dbo.tblRCat (RCatID);
ALTER TABLE dbo.tblRCatOmit
ADD CONSTRAINT FK_RCatOmit_countryId FOREIGN KEY (CountryId)
REFERENCES dbo.tblCountry (CountryID)

Related

Database contains foreign key that doesn exist even though there is a foreign key constraint?

I am working with a database where there is a foreign key ID that doesn't exist even though there is a foreign key constraint.
There is a table called "Workplace" with a foreign key column called "AddressID" pointing to another table called "Address"
The foreign key is as follows:
ALTER TABLE [dbo].[Workplace] WITH NOCHECK ADD CONSTRAINT [FK_Workplace_Address] FOREIGN KEY([AddressID])
REFERENCES [dbo].[Address] ([ID])
GO
ALTER TABLE [dbo].[Workplace] CHECK CONSTRAINT [FK_Workplace_Address]
GO
For one particular row in the Workplace table, the AddressID has a value of "1".
When I run select * from Address where ID = 1 there is no result.
Then I ran update Workplace set AddressID = 3 where Workplace.ID = 20 the value changed to 3 and I have verified that an Address with ID 3 exists.
Then I ran update Workplace set AddressID = 1 where Workplace.ID = 20 again and I get the error
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Workplace_Address". The conflict occurred in database db_name, table "dbo.Address", column 'ID'.
I don't understand how the value 1 could have been put there in the first place. The Address with ID=1 couldn't have been deleted after the constraint was put in place. The constraint creation would also fail if the record was deleted in the first place. Does anyone know how this could be possible?
This is a database on Windows Server 2016, SQL Server 12.0.4237.0
You create your FOREIGN KEY with NOCHECK, as a result the values that already exist in the table are not checked. This can be replicated with the following:
CREATE TABLE dbo.Address (ID int NOT NULL CONSTRAINT PK_Address PRIMARY KEY);
GO
CREATE TABLE dbo.Workplace (ID int NOT NULL CONSTRAINT PK_Workplace PRIMARY KEY,
AddressID int)
GO
INSERT INTO dbo.Workplace
VALUES(1,3); --Works
GO
ALTER TABLE dbo.WorkPlace WITH NOCHECK ADD CONSTRAINT FK_Workplace_Address FOREIGN KEY (AddressID) REFERENCES dbo.Address(ID);
GO
ALTER TABLE dbo.Workplace CHECK CONSTRAINT FK_Workplace_Address;
GO
INSERT INTO dbo.Workplace
VALUES(2,3); --Fails
GO
UPDATE dbo.Workplace
SET AddressID = 2
WHERE ID = 1; --Fails
GO
DROP TABLE dbo.Workplace;
DROP TABLE dbo.Address;
As you can see, only rows that are INSERTed or UPDATEd after the constraint was created (with NOCHECK) are validated; the first row INSERTed is left as it was, with a reference to a row that does not exist.
Instead, create the key without NOCHECK defined, or with CHECK, and the statement will fail when you try to create it:
CREATE TABLE dbo.Address (ID int NOT NULL CONSTRAINT PK_Address PRIMARY KEY);
GO
CREATE TABLE dbo.Workplace (ID int NOT NULL CONSTRAINT PK_Workplace PRIMARY KEY,
AddressID int)
GO
INSERT INTO dbo.Workplace
VALUES(1,3); --Works
GO
ALTER TABLE dbo.WorkPlace WITH CHECK ADD CONSTRAINT FK_Workplace_Address FOREIGN KEY (AddressID) REFERENCES dbo.Address(ID); --Fails
GO
DROP TABLE dbo.Workplace;
DROP TABLE dbo.Address;
This generates the error below:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Workplace_Address". The conflict occurred in database "Sandbox", table "dbo.Address", column 'ID'.
Alternatively, create the key when you create the tables; though it's likely too late for that now.
CREATE TABLE dbo.Address (ID int NOT NULL CONSTRAINT PK_Address PRIMARY KEY);
GO
CREATE TABLE dbo.Workplace (ID int NOT NULL CONSTRAINT PK_Workplace PRIMARY KEY,
AddressID int CONSTRAINT FK_Workplace_Address FOREIGN KEY REFERENCES dbo.Address(ID));
GO
INSERT INTO dbo.Workplace
VALUES(1,3); --Fails
GO
DROP TABLE dbo.Workplace;
DROP TABLE dbo.Address;

How to add to column type a "delete on cascade" in SQL Server?

I built a big database with many tables. After that I forgat to add "delete on cascade". How do I add the "delete on casade" on the specific columns I want ?
For example:
create table Users
(
ID char(9) primary key check (ID like replicate('[0-9]',9)),
firstName nvarchar(20) not null,
)
And
create table Applications
(
name nvarchar(20) primary key,
establishDate date not null
)
How do I alter this table-registered to, so that when I delete an app or users it deletes the rows that has this value?
create table RegisteredTo
(
userID char(9) references Users(ID),
ApplicationName nvarchar(20) references Applications(name),
primary key(userID, ApplicationName)
)
I tried something like that - but I got errors.
alter table RegisteredTo
ALTER COLUMN applicationName references Applications(name) ON DELETE CASCADE
nvarchar(20)
You need to add a FOREIGN CONSTRAINT and ON DELETE CASCADE:
ALTER TABLE RegisteredTo
ADD CONSTRAINT FK_RegisteredTo_Users FOREIGN KEY (userID) REFERENCES Users(ID) ON DELETE CASCADE;
ALTER TABLE RegisteredTo
ADD CONSTRAINT FK_RegisteredTo_Applications FOREIGN KEY (ApplicationName) REFERENCES Applications(name) ON DELETE CASCADE;

azure db drop pk and add a new one

I have MS SQL database on Azure , and I want to drop my Primary key constraint and add another column as a primary key , every time I try to run the script to drop the primary key I get the error:
" Tables without a clustered index are not supported in this version of SQL Server. Please create a clustered index and try again."
by running this script:
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.Paypaltransaction') AND Name = 'PK_PaypalTransaction')
ALTER TABLE dbo.PaypalTransaction
DROP CONSTRAINT PK_PaypalTransaction
GO
Then I go and try to create another primary key :
-- add new primary key constraint on new column
ALTER TABLE dbo.PaypalTransaction
ADD CONSTRAINT PK_PaypalTransactionId
PRIMARY KEY CLUSTERED (PaypalTransactionId)
GO
and I get this error:
"Table 'PaypalTransaction' already has a primary key defined on it."
I understand the error's , but I can't delete the primary key because it appearently has to have one , and I can't add a new one because I already have one . Am I just stuck forever and ever and ever with the wrong column as my primary key :'(
I see This Question here that is the same and they ended up dropping the table and creating a new one - no way that is the only way to do this , that is just silly.
Copy over from the DBA.Se answer:
Q5) Can the primary key of a table be modified when is enforced via the clustered index if the table is populated?
A: No. Any operation that converts a populated clustered index into a heap will be blocked in SQL Azure, even if the table is empty:
create table Friend (
UserId int not null,
Id int not null identity(1,1),
constraint pk_Friend primary key clustered (UserId, Id));
go
insert into Friend (UserId) values (1);
delete from Friend;
go
alter table Friend drop constraint pk_Friend;
As a side note: the constraint can be modified if the table is truncated.
The workaround to change the PK constraint of a populated table is to do the good old sp_rename trick:
create table Friend (
UserId int not null,
Id int not null identity(1,1),
constraint pk_Friend primary key clustered (UserId, Id));
go
insert into Friend (UserId) values (1);
go
create table FriendNew (
UserId int not null,
Id int not null identity(1,1),
constraint pk_Friend_New primary key clustered (Id, UserId));
go
set identity_insert FriendNew on;
insert into FriendNew (UserId, Id)
select UserId, Id
from Friend;
set identity_insert FriendNew off;
go
begin transaction
exec sp_rename 'Friend', 'FriendOld';
exec sp_rename 'FriendNew', 'Friend';
commit;
go
sp_help 'Friend';
The sp_rename approach has some issues, most importantly being that permissions on the table do not carry over during the rename, as well as foreign key constraints.
I have just tested and it seems that on SQL AZURE V12 it is possible!

Sql Error UserID, RoleId invalid Column Name on Login Asp.Net MVC

I have a web app using entity framework 6. Identity 2. MVC 4.
I will try to explain the things I was working on leading up to this error:
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'RoleId'.
Source Error: //In the Account Controller.cs
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
First, I added a relationship between AspNetUser table and a custom table "CustomerTicketInfo" in the Entity Designer. I Updated the Db from the Model and ran this auto generated Sql:
-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
-- --------------------------------------------------
-- Date Created: 08/13/2014 10:15:49
-- Generated from EDMX file: C:\Projects\DevTeam\Logistics Mobile MVC\LMSMobile\LMSMobile\Models\LogisticsManagementModel.edmx
-- --------------------------------------------------
SET QUOTED_IDENTIFIER OFF;
GO
USE [LTGLogisticsManagement];
GO
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
GO
-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- --------------------------------------------------
IF OBJECT_ID(N'[dbo].[FK_dbo_AspNetUserClaims_dbo_AspNetUsers_User_Id]', 'F') IS NOT NULL
ALTER TABLE [dbo].[AspNetUserClaims] DROP CONSTRAINT [FK_dbo_AspNetUserClaims_dbo_AspNetUsers_User_Id];
GO
IF OBJECT_ID(N'[dbo].[FK_dbo_AspNetUserLogins_dbo_AspNetUsers_UserId]', 'F') IS NOT NULL
ALTER TABLE [dbo].[AspNetUserLogins] DROP CONSTRAINT [FK_dbo_AspNetUserLogins_dbo_AspNetUsers_UserId];
GO
IF OBJECT_ID(N'[dbo].[FK_AspNetUserRoles_AspNetRole]', 'F') IS NOT NULL
ALTER TABLE [dbo].[AspNetUserRoles] DROP CONSTRAINT [FK_AspNetUserRoles_AspNetRole];
GO
IF OBJECT_ID(N'[dbo].[FK_AspNetUserRoles_AspNetUser]', 'F') IS NOT NULL
ALTER TABLE [dbo].[AspNetUserRoles] DROP CONSTRAINT [FK_AspNetUserRoles_AspNetUser];
GO
IF OBJECT_ID(N'[dbo].[FK_AspNetRoles_AspNetRoles]', 'F') IS NOT NULL
ALTER TABLE [dbo].[AspNetRoles] DROP CONSTRAINT [FK_AspNetRoles_AspNetRoles];
GO
IF OBJECT_ID(N'[dbo].[FK_AspNetUsers_AspNetUsers]', 'F') IS NOT NULL
ALTER TABLE [dbo].[AspNetUsers] DROP CONSTRAINT [FK_AspNetUsers_AspNetUsers];
GO
IF OBJECT_ID(N'[dbo].[FK_AspNetUserCustomerTicketInfo]', 'F') IS NOT NULL
ALTER TABLE [dbo].[CustomerTicketInfoes] DROP CONSTRAINT [FK_AspNetUserCustomerTicketInfo];
GO
-- --------------------------------------------------
-- Dropping existing tables
-- --------------------------------------------------
IF OBJECT_ID(N'[dbo].[CustomerTicketInfoes]', 'U') IS NOT NULL
DROP TABLE [dbo].[CustomerTicketInfoes];
GO
IF OBJECT_ID(N'[dbo].[AspNetRoles]', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetRoles];
GO
IF OBJECT_ID(N'[dbo].[AspNetUserClaims]', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUserClaims];
GO
IF OBJECT_ID(N'[dbo].[AspNetUserLogins]', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUserLogins];
GO
IF OBJECT_ID(N'[dbo].[AspNetUsers]', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUsers];
GO
IF OBJECT_ID(N'[dbo].[AspNetUserRoles]', 'U') IS NOT NULL
DROP TABLE [dbo].[AspNetUserRoles];
GO
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
-- Creating table 'CustomerTicketInfoes'
CREATE TABLE [dbo].[CustomerTicketInfoes] (
[Oid] uniqueidentifier NOT NULL,
[Commodity] nvarchar(100) NULL,
[ContractLocale] nvarchar(100) NULL,
[ArrivalNumber] nvarchar(100) NULL,
[PickUpNumber] nvarchar(100) NULL,
[OriginSignature] nvarchar(100) NULL,
[DestinationSignature] nvarchar(100) NULL,
[OptimisticLockField] int NULL,
[GCRecord] int NULL,
[Trucker] nvarchar(50) NULL,
[AspNetUserId] varchar(50) NOT NULL
);
GO
-- Creating table 'AspNetRoles'
CREATE TABLE [dbo].[AspNetRoles] (
[Id] varchar(50) NOT NULL,
[Name] nvarchar(max) NOT NULL
);
GO
-- Creating table 'AspNetUserClaims'
CREATE TABLE [dbo].[AspNetUserClaims] (
[Id] varchar(50) NOT NULL,
[ClaimType] nvarchar(max) NULL,
[ClaimValue] nvarchar(max) NULL,
[User_Id] varchar(50) NOT NULL
);
GO
-- Creating table 'AspNetUserLogins'
CREATE TABLE [dbo].[AspNetUserLogins] (
[UserId] varchar(50) NOT NULL,
[LoginProvider] nvarchar(128) NOT NULL,
[ProviderKey] nvarchar(128) NOT NULL
);
GO
-- Creating table 'AspNetUsers'
CREATE TABLE [dbo].[AspNetUsers] (
[Id] varchar(50) NOT NULL,
[UserName] nvarchar(max) NULL,
[PasswordHash] nvarchar(max) NULL,
[SecurityStamp] nvarchar(max) NULL,
[Discriminator] nvarchar(128) NOT NULL
);
GO
-- Creating table 'AspNetUserRoles'
CREATE TABLE [dbo].[AspNetUserRoles] (
[AspNetRoles_Id] varchar(50) NOT NULL,
[AspNetUsers_Id] varchar(50) NOT NULL
);
GO
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
-- Creating primary key on [Oid] in table 'CustomerTicketInfoes'
ALTER TABLE [dbo].[CustomerTicketInfoes]
ADD CONSTRAINT [PK_CustomerTicketInfoes]
PRIMARY KEY CLUSTERED ([Oid] ASC);
GO
-- Creating primary key on [Id] in table 'AspNetRoles'
ALTER TABLE [dbo].[AspNetRoles]
ADD CONSTRAINT [PK_AspNetRoles]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
-- Creating primary key on [Id] in table 'AspNetUserClaims'
ALTER TABLE [dbo].[AspNetUserClaims]
ADD CONSTRAINT [PK_AspNetUserClaims]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
-- Creating primary key on [UserId], [LoginProvider], [ProviderKey] in table 'AspNetUserLogins'
ALTER TABLE [dbo].[AspNetUserLogins]
ADD CONSTRAINT [PK_AspNetUserLogins]
PRIMARY KEY CLUSTERED ([UserId], [LoginProvider], [ProviderKey] ASC);
GO
-- Creating primary key on [Id] in table 'AspNetUsers'
ALTER TABLE [dbo].[AspNetUsers]
ADD CONSTRAINT [PK_AspNetUsers]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
-- Creating primary key on [AspNetRoles_Id], [AspNetUsers_Id] in table 'AspNetUserRoles'
ALTER TABLE [dbo].[AspNetUserRoles]
ADD CONSTRAINT [PK_AspNetUserRoles]
PRIMARY KEY CLUSTERED ([AspNetRoles_Id], [AspNetUsers_Id] ASC);
GO
-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------
-- Creating foreign key on [User_Id] in table 'AspNetUserClaims'
ALTER TABLE [dbo].[AspNetUserClaims]
ADD CONSTRAINT [FK_dbo_AspNetUserClaims_dbo_AspNetUsers_User_Id]
FOREIGN KEY ([User_Id])
REFERENCES [dbo].[AspNetUsers]
([Id])
ON DELETE CASCADE ON UPDATE NO ACTION;
-- Creating non-clustered index for FOREIGN KEY 'FK_dbo_AspNetUserClaims_dbo_AspNetUsers_User_Id'
CREATE INDEX [IX_FK_dbo_AspNetUserClaims_dbo_AspNetUsers_User_Id]
ON [dbo].[AspNetUserClaims]
([User_Id]);
GO
-- Creating foreign key on [UserId] in table 'AspNetUserLogins'
ALTER TABLE [dbo].[AspNetUserLogins]
ADD CONSTRAINT [FK_dbo_AspNetUserLogins_dbo_AspNetUsers_UserId]
FOREIGN KEY ([UserId])
REFERENCES [dbo].[AspNetUsers]
([Id])
ON DELETE CASCADE ON UPDATE NO ACTION;
GO
-- Creating foreign key on [AspNetRoles_Id] in table 'AspNetUserRoles'
ALTER TABLE [dbo].[AspNetUserRoles]
ADD CONSTRAINT [FK_AspNetUserRoles_AspNetRole]
FOREIGN KEY ([AspNetRoles_Id])
REFERENCES [dbo].[AspNetRoles]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating foreign key on [AspNetUsers_Id] in table 'AspNetUserRoles'
ALTER TABLE [dbo].[AspNetUserRoles]
ADD CONSTRAINT [FK_AspNetUserRoles_AspNetUser]
FOREIGN KEY ([AspNetUsers_Id])
REFERENCES [dbo].[AspNetUsers]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Creating non-clustered index for FOREIGN KEY 'FK_AspNetUserRoles_AspNetUser'
CREATE INDEX [IX_FK_AspNetUserRoles_AspNetUser]
ON [dbo].[AspNetUserRoles]
([AspNetUsers_Id]);
GO
-- Creating foreign key on [Id] in table 'AspNetRoles'
ALTER TABLE [dbo].[AspNetRoles]
ADD CONSTRAINT [FK_AspNetRoles_AspNetRoles]
FOREIGN KEY ([Id])
REFERENCES [dbo].[AspNetRoles]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating foreign key on [Id] in table 'AspNetUsers'
ALTER TABLE [dbo].[AspNetUsers]
ADD CONSTRAINT [FK_AspNetUsers_AspNetUsers]
FOREIGN KEY ([Id])
REFERENCES [dbo].[AspNetUsers]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating foreign key on [AspNetUserId] in table 'CustomerTicketInfoes'
ALTER TABLE [dbo].[CustomerTicketInfoes]
ADD CONSTRAINT [FK_AspNetUserCustomerTicketInfo]
FOREIGN KEY ([AspNetUserId])
REFERENCES [dbo].[AspNetUsers]
([Id])
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Creating non-clustered index for FOREIGN KEY 'FK_AspNetUserCustomerTicketInfo'
CREATE INDEX [IX_FK_AspNetUserCustomerTicketInfo]
ON [dbo].[CustomerTicketInfoes]
([AspNetUserId]);
GO
-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
After running that Sql it created a new table called CustomerTicketInfoes which has the AspNetUser relationship that I wanted (but it's no longer using my originally created table).
I then Enabled Migration Using PM. And I updated Model From database since there was a new table created.
I'm not sure if any of this has anything to do with the error. But this is what I was working on when I got the error above. Simply trying to login to the web app. with a registered Username + Pass. I also tried a different browser thinking it had something to do with cookies. Still fails.
Any input would be appreciated.
Rename the Fields of Table AspNetUserRoles
a. From `AspNetRole_Id` to `RoleId`
b. From `AspNetUser_Id` to `UserId`
Update Model From Database
Try Login it will work fine now.
It seems like it must be using the wrong tables, no? Perhaps in your db context class, applicationdbcontext in the default version, so just explicitly set the table names, something like
protected override void OnModelCreating(DbModelBuilder modelBuilder)
base.OnModelCreating(modelBuilder); // This needs to go before the other rules!
modelBuilder.Entity<User>().ToTable("AspnetUser");
modelBuilder.Entity<Role>().ToTable("AspnetRoles");
modelBuilder.Entity<UserRole>().ToTable("etc");
modelBuilder.Entity<UserLogin>().ToTable("etc");
modelBuilder.Entity<UserClaim>().ToTable("etc");
}

How can apply truncate command on a table which is referenced in another table?

I have two table masterTbl and detailTbl which structure is given below...
--PRIMARY TABLE
CREATE TABLE masterTbl (
id INT IDENTITY(1,1) CONSTRAINT pk_id PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description VARCHAR(max))
--FORIGN TABLE
CREATE TABLE detailTbl (
id INT IDENTITY(1,1) PRIMARY KEY,
m_id INT NOT NULL CONSTRAINT fk_mid FOREIGN KEY REFERENCES masterTbl(id) ON DELETE CASCADE,
details VARCHAR(MAX))
I want to perform
TRUNCATE TABLE masterTbl
but it is encountering error "Cannot truncate table 'testDB.dbo.masterTbl' because it is being referenced by a FOREIGN KEY constraint."
How can i use TRUNCATE command on masterTbl??
You have to remove the FK constraint fk_mid.
But you won't be able to put it back if the FK Constraint is not respected, cause the CASCADE REMOVE won't happen (risk of orphans)
Or use DELETE instead of TRUNCATE.
Which will preserve the DELETE CASCADE behaviour.
EDIT
DELETE FROM dbo.masterTbl;
DBCC CHECKIDENT ('dbo.masterTbl', RESEED, 0) -- will set IDENTITY count back to 0