Incorrect FK CONSTRAINT syntax migration output as part of CREATE TABLE
targetFramework="net451" version="7.0.0-beta4-12242"
On apply migration this gets sent to database
CREATE TABLE [Zoo] (
[City] nvarchar(max),
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max),
CONSTRAINT [PK_Zoo] PRIMARY KEY NONCLUSTERED ([Id])
);
CREATE TABLE [Animal] (
[Group] int NOT NULL,
[Id] int NOT NULL IDENTITY,
[Name] nvarchar(max),
[Weight] real NOT NULL,
[ZooId] int,
CONSTRAINT [PK_Animal] PRIMARY KEY NONCLUSTERED ([Id]),
CONSTRAINT [FK_Animal_Zoo_ZooId] FOREIGN KEY ([ZooId]) REFERENCES [Id].[Zoo] ()
);
CREATE TABLE [ZooAnimalSighting] (
[AnimalId] int,
[DateOf] datetime2 NOT NULL,
[Id] int NOT NULL IDENTITY,
[IsSightingReliable] bit NOT NULL,
[Sighter] nvarchar(max),
CONSTRAINT [PK_ZooAnimalSighting] PRIMARY KEY NONCLUSTERED ([Id]),
CONSTRAINT [FK_ZooAnimalSighting_Animal_AnimalId] FOREIGN KEY ([AnimalId]) REFERENCES [Id].[Animal] ()
);
CREATE TABLE [dbo].[__MigrationHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ContextKey] nvarchar(300) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK_MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])
)
INSERT INTO [dbo].[__MigrationHistory] ([MigrationId], [ContextKey], [ProductVersion])
VALUES ('20150213210349_InitialCreate', 'SightingsWebApp.DAL.ZooSightingDemoDb', '7.0.0-beta4-12242')
Note the () at end of FK Contraint def. this causes sql error.
PM> Apply-Migration -Context ZooSightingDemoDb -Verbose -Project Sightings.Web
Using project 'src\Sightings.Web'
Build started...
Build succeeded.
Using start-up project 'Sightings.Web'.
Using application base 'c:\projects\2013\Sightings\Sightings.Web\bin'.
Using application configuration 'c:\projects\2013\Sightings\Sightings.Web\Web.config'
Using data directory 'C:\projects\2013\Sightings\Sightings.Web\App_Data'
Using assembly 'Sightings.Web.dll'.
Using current directory 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE'.
Using context 'ZooSightingDemoDb'.
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'.
Incorrect syntax near ')'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at Microsoft.Data.Entity.Relational.SqlStatementExecutor.<>c__DisplayClass7_0.<ExecuteNonQuery>b__0() at Microsoft.Data.Entity.Relational.SqlStatementExecutor.Execute(RelationalConnection connection, Func1 action)
at Microsoft.Data.Entity.Relational.SqlStatementExecutor.ExecuteNonQuery(RelationalConnection connection, DbTransaction transaction, IEnumerable1 sqlBatches) at Microsoft.Data.Entity.Relational.Migrations.Migrator.Execute(IEnumerable1 sqlBatches, Boolean first)
at Microsoft.Data.Entity.Relational.Migrations.Migrator.ApplyMigrations(String targetMigration)
at Microsoft.Data.Entity.Commands.MigrationTool.ApplyMigration(String migrationName, String contextTypeName)
at Microsoft.Data.Entity.Commands.Executor.ApplyMigrationImpl(String migrationName, String contextTypeName)
at Microsoft.Data.Entity.Commands.Executor.ApplyMigration.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.Data.Entity.Commands.Executor.OperationBase.Execute(Action action)
ClientConnectionId:b3de3155-ee8d-4101-bb03-d45e73778cef
Error Number:102,State:1,Class:15
Incorrect syntax near ')'.
Incorrect syntax near ')'.
PM>
//--------------- Domain Objects public class ZooAnimalSighting { public int Id { get; set; } public string Sighter { get; set; } public DateTime DateOf { get; set; } public bool IsSightingReliable { get; set; } }
public class Zoo
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public float Weight { get; set; }
public AnimalGroup Group { get; set; }
}
public enum AnimalGroup
{
Invertebrate,
Fish,
Amphibian,
Reptile,
Mammal,
Bird
}
//--------------------- DbContext
public class ZooSightingDemoDb : DbContext
{
public DbSet
public DbSet<ZooAnimalSighting> Sightings { get; set; }
protected override void OnConfiguring(DbContextOptions builder)
{
builder.UseSqlServer(@"Server=Glenn-PC\SQLEXPRESS;Database=ZooSightingDemo2;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Zoo>()
.HasMany<Animal>();
builder.Entity<ZooAnimalSighting>()
.HasOne<Animal>();
}
}
I used Fluent API to create relationships
builder.Entity<Zoo>()
.HasMany<Animal>();
builder.Entity<ZooAnimalSighting>()
.HasOne<Animal>();
This was working before todays version release.
I just checked, this occurs with no Fluent API use and just nav properties so I believe it is a bug
public class ZooAnimalSighting
{
public int ZooAnimalSightingId { get; set; }
public string Sighter { get; set; }
public DateTime DateOf { get; set; }
public bool IsSightingReliable { get; set; }
public virtual Animal Animal { get; set; }
}
public class Zoo
{
public int ZooId { get; set; }
public string Name { get; set; }
public string City { get; set; }
public virtual ICollection Animals { get; set; }
}
public class Animal
{
public int AnimalId { get; set; }
public string Name { get; set; }
public float Weight { get; set; }
public AnimalGroup? Group { get; set; }
public virtual Zoo Zoo { get; set; }
}
public enum AnimalGroup
{
Invertebrate,
Fish,
Amphibian,
Reptile,
Mammal,
Bird
}
Comparing versions sql output:
version="6.1.3-beta1" (successful, happens after table create)
ALTER TABLE [dbo].[Animals] ADD CONSTRAINT [FK_dbo.Animals_dbo.Zoos_Zoo_ZooId] FOREIGN KEY ([Zoo_ZooId]) REFERENCES [dbo].[Zoos] ([ZooId])
version="7.0.0-beta4-12242" (fails, part of table create)
CONSTRAINT [FK_Animal_Zoo_ZooId] FOREIGN KEY ([ZooId]) REFERENCES [Id].[Zoo] ()
What does the Up method of your migration look like?
Here is the code correctly escaped for GitHub, post above required a couple tweaks to compile because of lost generic types.
public class ZooSightingDemoDb : DbContext
{
public DbSet<Zoo> Zoos { get; set; }
public DbSet<Animal> Animals { get; set; }
public DbSet<ZooAnimalSighting> Sightings { get; set; }
protected override void OnConfiguring(DbContextOptions builder)
{
builder.UseSqlServer(@"Server=(localdb)\v11.0;Database=ZooSightingDemo;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Zoo>().HasMany<Animal>();
builder.Entity<ZooAnimalSighting>().HasOne<Animal>();
}
}
public class ZooAnimalSighting
{
public int Id { get; set; }
public string Sighter { get; set; }
public DateTime DateOf { get; set; }
public bool IsSightingReliable { get; set; }
}
public class Zoo
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public float Weight { get; set; }
public AnimalGroup Group { get; set; }
}
public enum AnimalGroup
{
Invertebrate,
Fish,
Amphibian,
Reptile,
Mammal,
Bird
}
Below is the Up migration that is generated for the given code. I confirm the invalid SQL behavior indicated by @swaggerloaf .
public override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
"Zoo",
x => new
{
City = x.Column("nvarchar(max)", nullable: true),
Id = x.Column("int", annotations: new Dictionary<string, string> { { "SqlServer:ValueGeneration", "Identity" } }),
Name = x.Column("nvarchar(max)", nullable: true)})
.PrimaryKey(x => x.Id, name: "PK_Zoo");
migrationBuilder.CreateTable(
"Animal",
x => new
{
Group = x.Column("int"),
Id = x.Column("int", annotations: new Dictionary<string, string> { { "SqlServer:ValueGeneration", "Identity" } }),
Name = x.Column("nvarchar(max)", nullable: true),
Weight = x.Column("real"),
ZooId = x.Column("int", nullable: true)})
.PrimaryKey(x => x.Id, name: "PK_Animal")
.ForeignKey(x => x.ZooId, "Zoo", "Id", name: "FK_Animal_Zoo_ZooId");
migrationBuilder.CreateTable(
"ZooAnimalSighting",
x => new
{
AnimalId = x.Column("int", nullable: true),
DateOf = x.Column("datetime2"),
Id = x.Column("int", annotations: new Dictionary<string, string> { { "SqlServer:ValueGeneration", "Identity" } }),
IsSightingReliable = x.Column("bit"),
Sighter = x.Column("nvarchar(max)", nullable: true)})
.PrimaryKey(x => x.Id, name: "PK_ZooAnimalSighting")
.ForeignKey(x => x.AnimalId, "Animal", "Id", name: "FK_ZooAnimalSighting_Animal_AnimalId");
}
We have encountered the same issue with our model as well.
EntityFramework 7.0.0-beta4-12290
I have the same issue.
migrationBuilder.CreateTable(
"AspNetUserLogins",
x => new
{
LoginProvider = x.Column("nvarchar(450)", nullable: true),
ProviderDisplayName = x.Column("nvarchar(max)", nullable: true),
ProviderKey = x.Column("nvarchar(450)", nullable: true),
UserId = x.Column("nvarchar(450)", nullable: true)
})
.PrimaryKey(x => new { x.LoginProvider, x.ProviderKey }, name: "PK_AspNetUserLogins")
.ForeignKey(x => x.UserId, "AspNetUsers", "Id", name: "FK_AspNetUserLogins_AspNetUsers_UserId");
generates
CREATE TABLE [AspNetUserLogins] ( [LoginProvider] nvarchar(450), [ProviderDisplayName] nvarchar(max), [ProviderKey] nvarchar(450), [UserId] nvarchar(450), CONSTRAINT [PK_AspNetUserLogins] PRIMARY KEY NONCLUSTERED ([LoginProvider], [ProviderKey]), CONSTRAINT [FK_AspNetUserLogins_AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [Id].[AspNetUsers] () );
And the migrator throws exception:
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'.
Doh, it looks like it's scaffolding the call to TableBuilder.ForeignKey wrong. It should be as follows.
.ForeignKey(x => x.DependentId, "PrincipalTable", principalColumns: new[] { "PrincipalId" }, name: "FK_Dependent_Principal_DependentId");
There should also be an overload that takes just a string instead of an array.
I have changed migration as you said.
migrationBuilder.CreateTable(
"AspNetUserLogins",
x => new
{
LoginProvider = x.Column("nvarchar(450)", nullable: true),
ProviderDisplayName = x.Column("nvarchar(max)", nullable: true),
ProviderKey = x.Column("nvarchar(450)", nullable: true),
UserId = x.Column("int")
})
.PrimaryKey(x => new { x.LoginProvider, x.ProviderKey }, name: "PK_AspNetUserLogins")
.ForeignKey(x => x.UserId, "AspNetUsers", principalColumns: new[] { "Id" }, name: "FK_AspNetUserLogins_AspNetUsers_UserId");
and it worked, generated script
CREATE TABLE [AspNetUserLogins] ( [LoginProvider] nvarchar(450), [ProviderDisplayName] nvarchar(max), [ProviderKey] nvarchar(450), [UserId] int NOT NULL, CONSTRAINT [PK_AspNetUserLogins] PRIMARY KEY NONCLUSTERED ([LoginProvider], [ProviderKey]), CONSTRAINT [FK_AspNetUserLogins_AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [AspNetUsers] ([Id]) );
Seems like the overloaded method which takes string instead of array generates wrong script.
Watch out also about this, that seems to be a related problem:
migrationBuilder.CreateIndex("IX_Blog_Code", "Blog", "Code", unique: true);
shoul be (passing string array, instead of a string, to choose the correct overload with unique):
migrationBuilder.CreateIndex("IX_Blog_Code", "Blog", new[] { "Code" }, unique: true);
otherwise the migration can't compile because of this error:
Migrations\20150228230355_InitialSchema.cs(19,13,19,87): error CS1502: The best overloaded method match for 'Microsoft.Data.Entity.Relational.Migrations.Builders.MigrationBuilder.CreateIndex(string, string, System.Collections.Generic.IReadOnlyList<string>, string, bool, System.Collections.Generic.IReadOnlyDictionary<string,string>)' has some invalid arguments
Migrations\20150228230355_InitialSchema.cs(19,66,19,72): error CS1503: Argument 3: cannot convert from 'string' to 'System.Collections.Generic.IReadOnlyList<string>'
that code is generated when you configure an unique index on the entity model:
builder.Entity<Blog>()
.Index(b => b.Code)
.IsUnique();