Migrating to identity with [Id] replacement - c#

I have an existing database with my users. But the [Id] column is just a number
[Id] BIGINT IDENTITY (1, 1) NOT NULL
CONSTRAINT [Users] PRIMARY KEY CLUSTERED ([Id] ASC)
I want to transfer all of my users to a new AspNetUsers table where
[Id] NVARCHAR (128) NOT NULL
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
I saw all the explanations on migrating, but I couldnt find how can I generate a new Id in SQL Insert statment. All examples show only how to transfer data from the old database to a new one.
Can someone please give me an example of SQL code that copies all the data from one table and inserts it to another table with new generated unique value.

The final script that worked:
INSERT INTO AspNetUsers
(
Id,
Email,
UserName,
.
.
.
)
SELECT
CAST(NEWID() AS NVARCHAR (128)),
Email,
UserName,
.
.
.
FROM Users

Related

MS Access create table from query c#

Unable to create table via
CREATE TABLE AAA (
[Percentage] Number(15),
[ID] AutoIncrement CONSTRAINT PRIMARY KEY ,
[CaseRecNo] Number(15),
[CaseName] Text,
[Amount] Currency
)
Gives Syntax Error,
How to set Number filed type double ?
The field size is a double by default. Create this table in access and you will see the result. You also need to name your constraint
CREATE TABLE AAAB (
[Percentage] NUMBER,
[ID] AutoIncrement CONSTRAINT MyFieldConstraint PRIMARY KEY ,
[CaseRecNo] Number,
[CaseName] Text,
[Amount] Currency
)

Relationship between Identity tables and Other tables in ASP.NET MVC 5

In ASP.NET MVC 5 project, the database and identity tables are created by code first, and i created other tables by SQL (not by code first) in this database, and i want to join User table with some table by user Id.
Say database called Qwerty and the identity tables are:
dbo.Users
dbo.Roles
dbo.UserClaims
... ect
I want to create tables by SQL like this:
Create Table Topic.Topic
(
TopicID int Primary key identity(1,1) not null,
TopicAddress nvarchar(255) not null
)
Create Table dbo.Bookmark
(
BookmarkID int Primary key identity(1,1) not null,
BookmarkDate datetime default getdate() not null,
UserID int constraint FK_Favorites_Users_UserID foreign key (UserID) references Users(UserID) not null
)
Topic table is created successfully, but when i run SQL code for Bookmark table, it give me error and mark Users (table name) word with red line
By default the primary key of Users is nvarchar, so, your foreign key should be defined with that type.
Create Table dbo.Bookmark
(
BookmarkID int Primary key identity(1,1) not null,
BookmarkDate datetime default getdate() not null,
UserID [nvarchar](128) constraint FK_Favorites_Users_UserID foreign key (UserID) references Users(UserID) not null
)

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_

I have two tables , one to one relationship i makes DetailsID of projectDetails FK in ID of projects table:
projects:
ID, //has FK With DetailsID in Details table & auto identity (1,1)
ProjectName,
Areas,
PaymentSystem,
ReceivedDate,
PropertyClassification,
ProjectImage
ProjectDetails:
DetailsID ,auto identity ( 1,1)
ProjectDetailName,
ProjectDetailImage
I am trying to insert new record in projects table , gives me this error at this line of code :
con.Open();
comm.ExecuteNonQuery(); // when execute
System.Data.SqlClient.SqlException: 'The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Projects_ProjectDetails". The conflict occurred in database "AlamaarRealEstate", table "dbo.ProjectDetails", column 'DetailsID'.
and this is my stored to insert :
ALTER proc [Insert_Project]
#Projectname NVARCHAR(MAX) ,
#areas NVARCHAR(MAX) ,
#Paymentsystem NVARCHAR(MAX) ,
#Receiveddate date ,
#Classification NVARCHAR(MAX) ,
#Projectimage Nvarchar(MAX)
as
INSERT INTO dbo.Projects
(
ProjectName,
Areas,
PaymentSystem,
ReceivedDate,
PropertyClassification,
ProjectImage
)
VALUES
(
#Projectname ,
#areas,
#Paymentsystem ,
#Receiveddate ,
#Classification,
#Projectimage
)
The question explains the answer. Referential Integrity is not maintained properly, you are trying to insert into a child table for which the master value does not exist. Please insert values to Project_details first. This will resolve your issue. If you did not what this to throw an error, just check the existence of the DetailID in Projects table before inserting.
Without more detail your question is hard to answer. For instance in your procedure you do explicit column naming for inserts and LEAVE OUT the column you are having a problem with. So if the proc was wrong it would be bombing with your example foreign key constraint error. But you are not even listing the 'ID' field to insert into with the procedure. So this is common if you are using an 'Identity' field to self seed, but you are claiming it is a foreign key. So like others have commented, without more code to show the exact way your tables are made it's hard to guess. Here is a self extracting example you could run that shows if a column is nullable and I had a key constraint it would work. Without the exact code of the tables as well as the proc it is hard to tell. What you gave is pseudo code.
USE Tester --just a test database I have, you can use whatever database you want
GO
IF OBJECT_ID('Projects') IS NOT NULL
DROP TABLE Projects
IF OBJECT_ID('ProjectDetails') IS NOT NULL
DROP TABLE ProjectDetails
create TABLE ProjectDetails
(
DetailsID INT CONSTRAINT PK_DetailsId PRIMARY KEY,
ProjectDetailName VARCHAR(32)
)
CREATE TABLE Projects
(
Id INT CONSTRAINT FK_Projects_ProjectDetails FOREIGN KEY (Id) REFERENCES ProjectDetails(DetailsId),
ProjectName varchar(32)
)
GO
IF OBJECT_ID('Insert_Project') IS NOT NULL
DROP PROC Insert_Project
GO
Create proc Insert_Project
#Projectname NVARCHAR(MAX)
as
INSERT INTO dbo.Projects ( ProjectName )
VALUES ( #Projectname )
GO
Select *
From dbo.Projects
EXEC dbo.Insert_Project #Projectname = N'Test' -- nvarchar(max)
Select *
From dbo.Projects

How can I stop ASP.NET Identity from Deleting a role if there's a UserId that has that role?

Here is the SQL for the tables:
CREATE TABLE [dbo].[AspNetUserRoles] (
[UserId] INT NOT NULL,
[RoleId] INT NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[AspNetRoles] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
);
CREATE TABLE [dbo].[AspNetRoles] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[AspNetUsers] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (MAX) NULL,
[LastName] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([UserName] ASC);
Can someone help me. What I would like is for when there is a user that has been assigned to a role then I would like an attempt to delete the role to fail.
Your issue arises from the line ON DELETE CASCADE.
This line means that all records with foreign keys that connect to the record to be deleted will themselves be deleted.
You probably want ON DELETE NO ACTION. This will do what you want. You should be able to find whether anything was deleted by the return value of the query call (- It should be an integer containing the number of lines changed).

Why is Entity Framework losing my indexes?

When I use a database initializer like DropCreateDatabaseAlways or MigrateDatabaseToLatestVersion to create my Entity Framework (5.0.0) database, the resulting schema does not include the indexes that I defined in my migrations, unlike when I create the database using Update-Database.
How can I configure the system so that it produces the same end result using a database initializer as it would when running the migrations in sequence?
Example migration
public override void Up()
{
CreateIndex("dbo.Users", "Username", unique:true);
}
Result from DropCreateDatabaseAlways (no index)
CREATE TABLE [dbo].[Users] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
[Username] NVARCHAR (50) NULL,
[Email] NVARCHAR (255) NULL,
CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Result from Update-Database (includes index)
CREATE TABLE [dbo].[Users] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
[Username] NVARCHAR (50) NULL,
[Email] NVARCHAR (255) NULL,
CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_Username]
ON [dbo].[Users]([Username] ASC);
The approach you have used is the "manual" code first migrations. Where you get to fiddle with the script. Automated migrations or drop create, EF just bangs a script together to match the table and Foreign keys and pops it out there. ie what you would have seen in the generated class before you added code. :-)
Use Automated Migrations/Create scenarios and just call SQL Command direct afterwards to add indexes from code. You have the SQL code to create indexes. Just trigger the initializer and follow up with create Index custom routine.

Categories