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

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
)

Related

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

Entity Framework - Composite Primary key, two foreign keys, DB First not generating model

I have been trying to handle translations in my database and also Entity Framework. I am generating the following tables but the translate model is not being generated by Entity Framework. I have tried numerous combinations but it won't generate. But, for some reason there is one LanguageTranslate model that IS being generated I think it's because there is just a regular primary key and only one foreign key.
Any ideas are very welcome? Thank you.
CREATE TABLE [dbo].[Merchant]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY
-- Other columns here
)
CREATE TABLE [dbo].[MerchantTranslate]
(
[MerchantId] INT NOT NULL,
[LanguageId] INT NOT NULL,
[Name] NCHAR(50) NOT NULL,
CONSTRAINT [PK_MerchantTranslate]
PRIMARY KEY ([MerchantId], [LanguageId]),
CONSTRAINT [FK_MerchantTranslate_ToMerchant]
FOREIGN KEY ([MerchantId]) REFERENCES [Merchant]([Id]),
CONSTRAINT [FK_MerchantTranslate_ToLanguage]
FOREIGN KEY ([LanguageId]) REFERENCES [Language]([Id])
)

Migrating to identity with [Id] replacement

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

SQL value contrains to another table data

I have a couple of tables, lets say I have a cars table and I have another table which hold all types of cars available(just to avoid multiple entries on the cars table) so I want a constraint on my cars table that has a "list/set" of types of cars FROM the TypesOFCar Table this table contains (Make, Model, etc..) how can I archive this.
I want it modular so I can just add another kind of car to the TypeOfCar table and it becomes available on the Cars table, thx in advance.
The best way to implement this would be through a foreign key constraint. Essentially, you derive your tables such like:
CREATE TABLE dbo.CarType
(
[Id] INT NOT NULL DEFAULT(1, 1),
[Description] VARCHAR(255) NOT NULL
CONSTRAINT PK_CarType PRIMARY KEY NONCLUSTERED ([Id])
)
CREATE TABLE dbo.Car
(
[Id] INT NOT NULL DEFAULT(1, 1),
[Registration] VARCHAR(7) NOT NULL,
[CarType_Id] INT NOT NULL
CONSTRAINT PK_Car PRIMARY KEY NONCLUSTERED ([Id]),
CONSTRAINT FK_Car_CarType_Id FOREIGN KEY ([CarType_Id]) REFERENCES dbo.CarType ([Id])
)
In those example tables, I create a foreign key constraint that maps the CarType_Id column of the Car table to the Id column of the CarType. This relationship enforces that a CarType item must exist for the value being specified in the Car table.
You want to add a CarType column to your Cars table and make it a foreign key to your TypeOfCar table.

Why does a newly created EF-entity throw an ID is null exception when trying to save?

I´m trying out entity framework included in VS2010 but ´ve hit a problem with my database/model generated from the graphical interface.
When I do:
user = dataset.UserSet.CreateObject();
user.Id = Guid.NewGuid();
dataset.UserSet.AddObject(user);
dataset.SaveChanges();
{"Cannot insert the value NULL into column 'Id', table 'BarSoc2.dbo.UserSet'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The table i´m inserting into looks like so:
-- Creating table 'UserSet'
CREATE TABLE [dbo].[UserSet] (
[Id] uniqueidentifier NOT NULL,
[Name] nvarchar(max) NOT NULL,
[Username] nvarchar(max) NOT NULL,
[Password] nvarchar(max) NOT NULL
);
GO
-- Creating primary key on [Id] in table 'UserSet'
ALTER TABLE [dbo].[UserSet]
ADD CONSTRAINT [PK_UserSet]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
Am I creating the object in the wrong way or doing something else basic wrong?
On the model for the fields which is defined as key, add the following attribute.
This key which is not marked as IDENTITY in database, Entity Framework give the exception
[Key]
[Display(Name = "Id")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
public int Id { get; set; }
You shouldn't have to set the ID property manually. It should be set automatically when you save. I assume you are using the standard template for Entity Framework, and not the Self-tracking entities template or POCOs template. If so, something along the following lines would seem more appropriate:
User user = new User();
dataset.AddToUsers(user);
dataset.SaveChanges();

Categories