Using Add-migration, I get the following code-first migration:
public partial class MyMigration : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Attachment", "EmployeePresentationID", "dbo.L_EmployeePresentation");
DropForeignKey("dbo.Attachment", "TopicID", "dbo.Topic");
DropForeignKey("dbo.Attachment", "UploaderID", "dbo.User");
}
public override void Down()
{
AddForeignKey("dbo.Attachment", "UploaderID", "dbo.User", "ID", cascadeDelete: true);
AddForeignKey("dbo.Attachment", "TopicID", "dbo.Topic", "ID");
AddForeignKey("dbo.Attachment", "EmployeePresentationID", "dbo.L_EmployeePresentation", "ID");
}
}
The code is shortened, but not modified. While the up-migration works well, the down-migration fails:
PM> Update-Database -verbose
Using StartUp project 'My_Project'.
Using NuGet project 'My_Project'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'My-Database' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201410131339480_MyMigration].
Applying explicit migration: 201410131339480_MyMigration.
IF object_id(N'[dbo].[FK_dbo.AttachedFile_dbo.L_EmpPr_EmpPrID]', N'F') IS NOT NULL
ALTER TABLE [dbo].[AttachedFile] DROP CONSTRAINT [FK_dbo.AttachedFile_dbo.L_EmpPr_EmpPrID]
IF object_id(N'[dbo].[FK_dbo.AttachedFile_dbo.Topic_TopicID]', N'F') IS NOT NULL
ALTER TABLE [dbo].[AttachedFile] DROP CONSTRAINT [FK_dbo.AttachedFile_dbo.Topic_TopicID]
IF object_id(N'[dbo].[FK_dbo.AttachedFile_dbo.User_UploaderID]', N'F') IS NOT NULL
ALTER TABLE [dbo].[AttachedFile] DROP CONSTRAINT [FK_dbo.AttachedFile_dbo.User_UploaderID]
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201410131339480_MyMigration', N'My_Project.DataLayer.DataContext',
/// LOOOOOOOONG hex-stuff
Running Seed method.
PM> Update-Database -Target tags_added -verbose
Using StartUp project 'My_Project'.
Using NuGet project 'My_Project'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'My-Database' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
Reverting migrations: [201410131339480_MyMigration].
Reverting explicit migration: 201410131339480_MyMigration.
ALTER TABLE [dbo].[AttachedFile] ADD CONSTRAINT [FK_dbo.AttachedFile_dbo.User_UploaderID] FOREIGN KEY ([UploaderID]) REFERENCES [dbo].[User] ([ID]) ON DELETE CASCADE
System.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN KEY constraint 'FK_dbo.AttachedFile_dbo.User_UploaderID' on table 'AttachedFile' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
....
Introducing FOREIGN KEY constraint 'FK_dbo.AttachedFile_dbo.User_UploaderID' on table 'AttachedFile' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
PM>
The Error baffles me, because the database has the foreign key at the moment. If this was impossible, I shouldn't have the current database, right?
Here is the table structure:
/****** Object: Table [dbo].[AttachedFile] Script Date: 10/14/2014 14:05:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AttachedFile](
[ID] [int] IDENTITY(1,1) NOT NULL,
[TopicID] [int] NULL,
[Deleted] [datetime] NULL,
[DisplayName] [nvarchar](max) NOT NULL,
[SafeName] [nvarchar](max) NOT NULL,
[Extension] [nvarchar](max) NOT NULL,
[Created] [datetime] NOT NULL,
[FileSize] [int] NOT NULL,
[UploaderID] [int] NOT NULL,
[EmployeePresentationID] [int] NULL,
CONSTRAINT [PK_dbo.AttachedFile] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[AttachedFile] WITH CHECK ADD CONSTRAINT [FK_dbo.AttachedFile_dbo.L_EmployeePresentation_EmployeePresentation_ID] FOREIGN KEY([EmployeePresentationID])
REFERENCES [dbo].[L_EmployeePresentation] ([ID])
GO
ALTER TABLE [dbo].[AttachedFile] CHECK CONSTRAINT [FK_dbo.AttachedFile_dbo.L_EmployeePresentation_EmployeePresentation_ID]
GO
ALTER TABLE [dbo].[AttachedFile] WITH CHECK ADD CONSTRAINT [FK_dbo.AttachedFile_dbo.Topic_TopicID] FOREIGN KEY([TopicID])
REFERENCES [dbo].[Topic] ([ID])
GO
ALTER TABLE [dbo].[AttachedFile] CHECK CONSTRAINT [FK_dbo.AttachedFile_dbo.Topic_TopicID]
GO
ALTER TABLE [dbo].[AttachedFile] WITH CHECK ADD CONSTRAINT [FK_dbo.AttachedFile_dbo.User_Uploader_ID] FOREIGN KEY([UploaderID])
REFERENCES [dbo].[User] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[AttachedFile] CHECK CONSTRAINT [FK_dbo.AttachedFile_dbo.User_Uploader_ID]
GO
/****** Object: Table [dbo].[User] Script Date: 10/14/2014 14:06:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Guid] [uniqueidentifier] NOT NULL,
[ShortName] [nvarchar](max) NOT NULL,
[LongName] [nvarchar](max) NULL,
[EmailAddress] [nvarchar](max) NULL,
[IsActive] [bit] NOT NULL,
[ActiveSession_ID] [int] NULL,
[Settings_ColorScheme] [int] NOT NULL,
[SessionReport_ID] [int] NULL,
[Settings_ReportOccasions] [int] NOT NULL,
CONSTRAINT [PK_dbo.User] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_dbo.User_dbo.ActiveSession_ActiveSession_ID] FOREIGN KEY([ActiveSession_ID])
REFERENCES [dbo].[ActiveSession] ([ID])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_dbo.User_dbo.ActiveSession_ActiveSession_ID]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_dbo.User_dbo.SessionReport_SessionReport_ID] FOREIGN KEY([SessionReport_ID])
REFERENCES [dbo].[SessionReport] ([ID])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_dbo.User_dbo.SessionReport_SessionReport_ID]
GO
ALTER TABLE [dbo].[User] ADD DEFAULT ((0)) FOR [Settings_ColorScheme]
GO
ALTER TABLE [dbo].[User] ADD DEFAULT ((0)) FOR [Settings_ReportOccasions]
GO
If a foreign key on the dependent entity is not nullable, then Code
First sets cascade delete on the relationship.
Reference:
EF Cascade on delete
So your down migration is adding a cascade on delete that didn't exist before the up migration. Use the FluentAPI method .WillCascadeOnDelete(false) to specify that that the foreign key should not cascade on delete.
Related
Trying to apply TPT inheritance in EF Core 5, using an existing schema. How can I specify the foreign key column name of the child table, if the column name does not exactly match the parent table? In the documentation example, we would not have Pets.Id, but Pets.PetId:
CREATE TABLE [Animals] (
[Id] int NOT NULL IDENTITY,
[Species] nvarchar(max) NULL,
CONSTRAINT [PK_Animals] PRIMARY KEY ([Id])
);
CREATE TABLE [Pets] (
*[PetId] int NOT NULL*,
[Name] nvarchar(max) NULL,
CONSTRAINT [PK_Pets] PRIMARY KEY ([PetId]),
CONSTRAINT [FK_Pets_Animals_Id] FOREIGN KEY ([PetId]) REFERENCES [Animals] ([Id]) ON DELETE NO ACTION
);
T-SQL Insert into multiple linked tables using a condition and without using a cursor.
Hello,
I have the following tables
CREATE TABLE [dbo].[TestMergeQuote](
[uid] [uniqueidentifier] NOT NULL,
[otherData] [nvarchar](50) NULL,
CONSTRAINT [PK_TestMergeQuote] PRIMARY KEY CLUSTERED
(
[uid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[TestMergeQuote] ADD CONSTRAINT [DF_TestMergeQuote_uid] DEFAULT (newid()) FOR [uid]
--=============
CREATE TABLE [dbo].[TestMergeClient](
[id] [int] IDENTITY(1,1) NOT NULL,
[otherData] [nvarchar](50) NULL,
CONSTRAINT [PK_TestMergeClient] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--==============
CREATE TABLE [dbo].[TestMergeDocument](
[id] [int] NOT NULL,
[uid_quote] [uniqueidentifier] NOT NULL,
[id_owner] [int] NOT NULL,
[id_keeper] [int] NULL,
[otherData] [nvarchar](50) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TestMergeDocument] WITH CHECK ADD CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Keeper] FOREIGN KEY([id_keeper])
REFERENCES [dbo].[TestMergeClient] ([id])
GO
ALTER TABLE [dbo].[TestMergeDocument] CHECK CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Keeper]
GO
ALTER TABLE [dbo].[TestMergeDocument] WITH CHECK ADD CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Owner] FOREIGN KEY([id_owner])
REFERENCES [dbo].[TestMergeClient] ([id])
GO
ALTER TABLE [dbo].[TestMergeDocument] CHECK CONSTRAINT [FK_TestMergeDocument_TestMergeClient_Owner]
GO
ALTER TABLE [dbo].[TestMergeDocument] WITH CHECK ADD CONSTRAINT [FK_TestMergeDocument_TestMergeQuote] FOREIGN KEY([uid_quote])
REFERENCES [dbo].[TestMergeQuote] ([uid])
GO
ALTER TABLE [dbo].[TestMergeDocument] CHECK CONSTRAINT [FK_TestMergeDocument_TestMergeQuote]
GO
AND also table X with other various data.
I want to insert into these three tables the data that already exists in these 3 tables, but giving it different id's, and also replacing some of the data within the X table.
It's a sort of a "copy the data from last year", but add new info.
The condition is that id_keeper is sometimes null, and no insert should be done for it.
I am aware that I have to use OUTPUT and MERGE, but I have no ideea how to achieve something this complex.
The CRUDE code for this using a cursor would be:
DECLARE #OldIdDocument INT, #NewIdDocument INT
DECLARE #OldIdOwner INT, #NewIdOwner INT
DECLARE #OldIdKeeper INT, #NewIdKeeper INT
DECLARE #OldIdQuote UNIQUEINDETIFIER, #NewIdQuote UNIQUEINDETIFIER,
INSERT INTO TestMergeQuote(otherData)
SELECT TOP(1) otherData FROM TestMergeQuote WHERE uid = #OldIdQuote
SET #NewIdQuote = ##IDENTITY
INSERT INTO TestMergeClient(otherData)
SELECT TOP(1) otherData FROM TestMergeClient WHERE uid = #OldIdOwner
SET #NewIdOwner = ##IDENTITY
IF(#OldIdKeeper IS NOT NULL)
BEGIN
INSERT INTO TestMergeClient(otherData)
SELECT TOP(1) otherData FROM TestMergeClient WHERE uid = #OldIdKeeper
SET #NewIdKeeper = ##IDENTITY
END
INSERT INTO TestMergeDocument([uid_quote], [id_owner] , [id_keeper], otherData)
SELECT TOP(1) #NewIdQuote , #NewIdOwner , #NewIdKeeper ,otherData FROM TestMergeDocument WHERE uid = #OldIdDocument
SET #NewIdDocument = ##IDENTITY
You shouldn't have to use a cursor. What I would try is to first pump the data out into separate tables so you can manipulate the data to your heart's content.
Something like this first:
select * into TestMergeQuote_Temp from TestMergeQuote
That will make a new table with the data you want to copy. Of course you can add a where clause to filter the data so you aren't copying a very large table.
Then you can add values, change values, delete values on the _Temp versions.
When you are ready you can insert the data back. Of course you might have to turn auto id off if you have a primary key that is auto-incrementing. Or if you just want new id's and don't want to make id's manually, you should be able to insert the new records just fine and have new id's created for you.
But as a start, try pumping the data into new tables and then worry about inserting after that.
I've got a problem I can't figure out how to express with CTP5 of Code First and EF4.
EDIT: Added my old schema at the bottom that I'd like to replicate through CF
Here's my specific scenario:
A Team is an abstract concept; it should exist with a specific set of players, in a specific division, in a specific season.
A concrete example of this in action from the NFL:
1996 (season) AFC Central (division) Houston Oilers (team)
1997 (season) AFC Central (division) Tennessee Oilers (team)
1999 (season) AFC Central (division) Tennessee Titans (team)
2002 (season) AFC South (division) Tennessee Titans (team)
These are all the same team. I want to be able to do the following:
// Titans team id = 17
var myTeam = myContext.Teams.Single(t => t.Id == 17)
// display players
foreach (var p in myTeam.Seasons[1999].Players)
{
// Do something with the p here
}
// Display current division
Response.Write(myTeam.Seasons[2002].Division.Name);
I'm not sure of the specific query syntax within an ICollection member variable of myTeam.Seasons, but the concept should be the same none the less.
Can anyone shed some light on how you'd express this concept through CF in EF4 CF CTP5?
How would you express this through Code First?
Current SQL tables
CREATE TABLE dbo.Season
(
Id INT IDENTITY(1,1) NOT NULL,
LeagueId INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Year] CHAR(4) NOT NULL,
PrevSeasonId INT NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Season WITH NOCHECK ADD
CONSTRAINT PK_Season PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY];
CREATE TABLE dbo.Division
(
Id INT IDENTITY(1,1) NOT NULL,
DefaultName NVARCHAR(50) NOT NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Division WITH NOCHECK ADD
CONSTRAINT PK_Division PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY];
// Key Relation Table
CREATE TABLE dbo.DivisionsInSeason
(
DivisionId INT NOT NULL,
SeasonId INT NOT NULL,
DefaultName NVARCHAR(50) NOT NULL,
Commissioner UNIQUEIDENTIFIER NOT NULL,
ParentDivId INT NULL
) ON [PRIMARY];
// Primary Key
ALTER TABLE dbo.DivisionsInSeason WITH NOCHECK ADD
CONSTRAINT PK_DivisionsInSeason PRIMARY KEY NONCLUSTERED (DivisionId, SeasonId) ON [PRIMARY] ;
// Foreign Keys
ALTER TABLE dbo.DivisionsInSeason WITH CHECK ADD
CONSTRAINT FK_DivisionsInSeason_Division FOREIGN KEY(DivisionId) REFERENCES dbo.Division(Id),
CONSTRAINT FK_DivisionsInSeason_Season FOREIGN KEY(SeasonId) REFERENCES dbo.Season(Id),
CONSTRAINT FK_DivisionsInSeason_User FOREIGN KEY(Commissioner) REFERENCES dbo.[User](Id);
CREATE TABLE dbo.Team
(
Id INT IDENTITY(1,1) NOT NULL,
DefaultName NVARCHAR(50) NOT NULL,
DefShortName NCHAR(3) NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Team WITH NOCHECK ADD
CONSTRAINT PK_Team PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY] ;
// Key relationship table
CREATE TABLE dbo.TeamsInDivision
(
TeamId INT NOT NULL,
DivisionId INT NOT NULL,
SeasonId INT NOT NULL,
GeneralManager UNIQUEIDENTIFIER NOT NULL,
Name NVARCHAR(50) NOT NULL,
ShortName NCHAR(3) NULL
) ON [PRIMARY];
// Check Constraints
ALTER TABLE dbo.TeamsInDivision ADD
CONSTRAINT PK_TeamsInDivision PRIMARY KEY NONCLUSTERED (TeamId, DivisionId, SeasonId) ON [PRIMARY];
// Foreign Keys
ALTER TABLE dbo.TeamsInDivision WITH CHECK ADD
CONSTRAINT FK_TeamsInDivision_Team FOREIGN KEY(TeamId) REFERENCES dbo.Team(Id),
CONSTRAINT FK_TeamsInDivision_Division FOREIGN KEY(DivisionId) REFERENCES dbo.Division(Id),
CONSTRAINT FK_TeamsInDivision_Season FOREIGN KEY(SeasonId) REFERENCES dbo.Season(Id),
CONSTRAINT FK_TeamsInDivision_User FOREIGN KEY(GeneralManager) REFERENCES dbo.[User](Id);
Maybe this could be usefull
http://blogs.microsoft.co.il/blogs/gilf/archive/2011/08/01/creating-a-many-to-many-mapping-using-code-first.aspx
Trying to map the following schema using the Entity Framework.
A Customer can have many associated Stores.
A Store can have many associated Customer
Each Store can have 0 or 1 and only 1 TopCustomer (the criteria to be a TopCustomer is determined in the business logic)
this results with the following mapping in VS.
Here's the DB Script :
USE [TestDb]
GO
/****** Object: Table [dbo].[Customer] Script Date: 06/20/2009 09:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[CustomerId] [uniqueidentifier] NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Store] Script Date: 06/20/2009 09:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Store](
[StoreId] [uniqueidentifier] NOT NULL,
[StoreName] [nvarchar](50) NOT NULL,
[TopCustomer] [uniqueidentifier] NULL,
CONSTRAINT [PK_Store] PRIMARY KEY CLUSTERED
(
[StoreId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[CustomerStore] Script Date: 06/20/2009 09:53:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CustomerStore](
[CustomerId] [uniqueidentifier] NOT NULL,
[StoreId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_CustomerStore] PRIMARY KEY CLUSTERED
(
[CustomerId] ASC,
[StoreId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: ForeignKey [FK_CustomerStore_Customer] Script Date: 06/20/2009 09:53:52 ******/
ALTER TABLE [dbo].[CustomerStore] WITH CHECK ADD CONSTRAINT [FK_CustomerStore_Customer] FOREIGN KEY([CustomerId])
REFERENCES [dbo].[Customer] ([CustomerId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CustomerStore] CHECK CONSTRAINT [FK_CustomerStore_Customer]
GO
/****** Object: ForeignKey [FK_CustomerStore_Store] Script Date: 06/20/2009 09:53:52 ******/
ALTER TABLE [dbo].[CustomerStore] WITH CHECK ADD CONSTRAINT [FK_CustomerStore_Store] FOREIGN KEY([StoreId])
REFERENCES [dbo].[Store] ([StoreId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CustomerStore] CHECK CONSTRAINT [FK_CustomerStore_Store]
GO
/****** Object: ForeignKey [FK_Store_TopCustomer] Script Date: 06/20/2009 09:53:52 ******/
ALTER TABLE [dbo].[Store] WITH CHECK ADD CONSTRAINT [FK_Store_TopCustomer] FOREIGN KEY([TopCustomer])
REFERENCES [dbo].[Customer] ([CustomerId])
GO
ALTER TABLE [dbo].[Store] CHECK CONSTRAINT [FK_Store_TopCustomer]
GO
Question :
How can the TopCustomer association be mapped to a single instance of Customer without creating an extra navigation property on the Customer class ?
It sounds like you have the model working and mapping already?
But you just need to remove the extra navigation property?
If you want to remove the navigation property it is pretty simple (although you can't do it the standard EF designer).
You simply open your EDMX file in an XML editor (easy enough inside VS) and delete the unwanted <NavigationProperty .../> from the Customer Entity.
This way the relationship still exists in the Model, but in the class you can only go from
Store.TopCustomer
you can't go the other way.
Hope this helps
Alex
Program Manager Entity Framework Team, Microsoft.
I am working on a pomotion database and below is what my CREATE TABLE steatment looks like:
CREATE TABLE [dbo].[sponsors]
(
[InstId] [bigint] NOT NULL,
[EncryptedData] [varbinary](44) NOT NULL,
[HashedData] [varbinary](22) NOT NULL,
[JobId] [bigint] NOT NULL,
CONSTRAINT [PK_sponsors] PRIMARY KEY CLUSTERED
(
[InstId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[sponsors] WITH CHECK ADD CONSTRAINT [FK_sponsors_jobs] FOREIGN KEY([JobId])
REFERENCES [dbo].[jobs] ([Id])
GO
ALTER TABLE [dbo].[sponsors] CHECK CONSTRAINT [FK_sponsors_jobs]
GO
ALTER TABLE [dbo].[sponsors] WITH CHECK ADD CONSTRAINT [FK_sponsors_titles] FOREIGN KEY([TId])
REFERENCES [dbo].[titles] ([TId])
GO
ALTER TABLE [dbo].[sponsors] CHECK CONSTRAINT [FK_sponsors_titles]
GO
And I'd like to get rid of ALTER TABLE statements and make them part of CREATE TABLE
statements, I know how to do the most but not sure how to get CHECK CONSTRAINT during
create table, does anyone have experience with this? or know how to?
You can just add each foreign key constraint right in the CREATE TABLE declaration:
CREATE TABLE [dbo].[sponsors]
(
[InstId] [bigint] NOT NULL,
[EncryptedData] [varbinary](44) NOT NULL,
[HashedData] [varbinary](22) NOT NULL,
[JobId] [bigint] NOT NULL,
[TId] [int] NOT NULL,
CONSTRAINT [PK_sponsors] PRIMARY KEY CLUSTERED
(
[InstId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [FK_sponsors_jobs] FOREIGN KEY([JobId])
REFERENCES [dbo].[jobs] ([Id]),
CONSTRAINT [FK_sponsors_titles] FOREIGN KEY([TId])
REFERENCES [dbo].[titles] ([TId])
) ON [PRIMARY]
You seem to have missed a column (TId)
CREATE TABLE [dbo].[sponsors]
(
[InstId] [bigint] NOT NULL
CONSTRAINT [PK_sponsors] PRIMARY KEY CLUSTERED,
[EncryptedData] varbinary NOT NULL,
[HashedData] varbinary NOT NULL,
[JobId] [bigint] NOT NULL
CONSTRAINT [FK_sponsors_jobs] FOREIGN KEY REFERENCES [dbo].[jobs] ([Id]),
[TId] int NOT NULL
CONSTRAINT [FK_sponsors_titles] FOREIGN KEY REFERENCES [dbo].[titles] ([TId])
) ON [PRIMARY]
The ALTER TABLE ... CHECK CONSTRAINT command simply enables (or disables with NOCHECK) the constraint. Constraints are enabled by default when you add them, so this extra statement is redundant and not needed if you are adding the constraints in the CREATE statement.
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx