EF Core 2 tries to create same table twice - entity-framework

I have a project using EF Core 2. I created a migration. When running the migration it returns with the following error:
infoinfo: System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'Clients' in the database.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 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(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite, String methodName)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:718d9d47-c2e4-4bf5-9e15-165884a5ff11
Error Number:2714,State:6,Class:16
infoerror: There is already an object named 'Clients' in the database.
: Microsoft.EntityFrameworkCore.Database.Command[200101]
Executed DbCommand (8ms) [Parameters=[#p0='?' (Size = 400), #p1='?' (Size = 400), #p2='?' (Size = 4000), #p3='?', #p4='?', #p5='?' (Size = 400), #p6='?' (Size = 400), #p7='?' (Size = 4000), #p8='?', #p9='?', #p10='?' (Size = 400), #p11='?' (Size = 400), #p12='?' (Size = 4000), #p13='?', #p14='?', #p15='?' (Size = 400), #p16='?' (Size = 400), #p17='?' (Size = 4000), #p18='?', #p19='?'], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
DECLARE #inserted0 TABLE ([Id] int, [_Position] [int]);
MERGE [Options] USING (
VALUES (#p0, #p1, #p2, #p3, #p4, 0),
(#p5, #p6, #p7, #p8, #p9, 1),
(#p10, #p11, #p12, #p13, #p14, 2),
(#p15, #p16, #p17, #p18, #p
This is my DbContext:
namespace MyProject.Data
{
public class MyProjectContext : DbContext
{
public MyProjectContext(DbContextOptions<MyProjectContext> options)
: base(options)
{
}
public DbSet<ExtensionBasicQuotation> ExtensionBasicQuotations { get; set; }
public DbSet<ExtensionSpecifiedQuotation> ExtensionSpecifiedQuotations { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<Option> Options { get; set; }
public DbSet<SpecifiedQuotationAttachment> SpecifiedQuotationAttachments { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new ClientConfiguration());
builder.ApplyConfiguration(new ExtensionBasicQuotationConfiguration());
builder.ApplyConfiguration(new ExtensionSpecifiedQuotationConfiguration());
builder.ApplyConfiguration(new OptionConfiguration());
}
}
}
There is only one migration and the migration has only one CreateTable function for the Clients table.
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Address = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: true),
City = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
Email = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
Name = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
Phone = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: true),
Postcode = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
Why is the Clients table created twice?

I found the same issue with EF Core 2.0
The problem shows up when creating a Seeder class and inside the seed method you have:
_ctx.Database.EnsureCreated();
Then if you add a migration (Initial or one with more tables) and execute the database update, the seeder will try to create the database first (but somehow not the version record in the history?) and then the update will try again.
Anyhow, commenting out the previous line in the seed method fixed the problem.

If this migration is the InitialCreate migration, it seems you shouldn't run it if you already have a database, it should be run only for creating a new database.
If you created the initial migration when the database already exists,
the database creation code is generated but it doesn't have to run
because the database already matches the data model. When you deploy
the app to another environment where the database doesn't exist yet,
this code will run to create your database
http://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations

I had a similar issue, database was created according to initial migration, but a migrations table was empty.
So the fix was to manually fill it:
MigrationName is located inside _migrationName_.Designer.cs file insite an attribute e.g. [Migration("20210209115216_InitialMigration")]
ProductVersion is located in the context's snapshot class e.g. MyDbContextModelSnapshot, there is a row .HasAnnotation("ProductVersion", "5.0.2");
I faced this lag during with an initial migration script, but I assume that it could be reproducible for any migration with a similar fix.

Related

Entity Framework Core in ASP.NET Core 3.1 Scaffold-DbContext when using named connection from appsetting

I am writing an ASP.NET Core 3.1 class library to Scaffold-DbContext to reverse engineering the tables into models.
It is throwing an error
Format of the initialization string does not conform to specification starting at index 0
if I use the connection string directly instead of -Connection it work without problem, but trying to understand what is that I am not doing correctly?
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"DatabaseConsString": "Server=tcp:mysqlserver.database.windows.net,1433;Initial Catalog=mysqldb;Persist Security Info=False;User ID=XXXXX;Password=XXXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}
The above is my appsetting.json file, and this is the command I use:
PM> Scaffold-DbContext -Connection Name=DatabaseConsString
Microsoft.EntityFrameworkCore.SqlServer -OutputDir DbModels
-Context myDbContext -UseDatabaseNames -Force
-Tables [dbo].[UserInfo],[dbo].[Transactions]
Build started...
Build succeeded.
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.
at Microsoft.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
at Microsoft.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 synonyms, Boolean firstKey)
at Microsoft.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary2 synonyms)
at Microsoft.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at Microsoft.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at Microsoft.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at Microsoft.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString)
at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerDatabaseModelFactory.Create(String connectionString, DatabaseModelFactoryOptions options)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffolder.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions databaseOptions, ModelReverseEngineerOptions modelOptions, ModelCodeGenerationOptions codeOptions)
at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String outputContextDir, String dbContextClassName, IEnumerable1 schemas, IEnumerable1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String outputDbContextDir, String dbContextClassName, IEnumerable1 schemaFilters, IEnumerable1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_01.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Format of the initialization string does not conform to specification starting at index 0.

EF Core, Invalid column name exception after update from netcore2.2 to netcore3.1

Since I've updated from .netcore2.2 to .netcore3.1, I'm facing new weird exception "Invalid column name 'TenantTemplateTypeID1'". Please not the '1', that shouldn't be here. There is NO TenantTemplateTypeID1 anywhere in the code, so I assume it's generated by EF core.
EF core version: 3.1.1
Exception:
Exception: Invalid column name 'TenantTemplateTypeID1'.
Invalid column name 'TenantTemplateTypeID1'.
Invalid column name 'TenantTemplateTypeID1'.
Invalid column name 'TenantTemplateTypeID1'.
StactTrace: at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
Query:
var t = engineCtx.TenantTemplates
.AsNoTracking()
.Include(tt => tt.TenantTemplateParameters)
.Include(tt => tt.TenantTemplateStyles)
.FirstOrDefault(tt => tt.TenantTemplateTypeID == tenantTemplateTypeID);
DbContext
modelBuilder.Entity<Db.Model.TenantTemplate>(entity =>
{
entity.HasKey(e => e.TenantTemplateTypeID)
.HasName("PK_TenantTemplate_TenantTemplateTypeID");
entity.ToTable("TenantTemplates", "templateEngine");
entity.Property(e => e.TenantTemplateTypeID)
.HasColumnName("TenantTemplateTypeId");
//... not related rows removed
entity.HasMany(e => e.TenantTemplateParameters)
.WithOne(e => e.TenantTemplate)
.HasConstraintName("FK_TenantTemplate_TenantTemplateParameters")
.OnDelete(DeleteBehavior.Restrict);
entity.HasMany(e => e.TenantTemplateStyles)
.WithOne(e => e.TenantTemplate)
.HasConstraintName("FK_TenantTemplate_TenantTemplateStyles")
.OnDelete(DeleteBehavior.Restrict);
});
DB model contains only properties without any attributes.
public partial class TenantTemplate
{
public long TenantTemplateTypeID { get; set; }
// not related rows removed
public virtual ICollection<TenantTemplateParameter> TenantTemplateParameters { get; set; }
public virtual ICollection<TenantTemplateStyle> TenantTemplateStyles { get; set; }
}
// TenantTemplateStyle is exacly the same (just PK has a different name)
public class TenantTemplateParameter
{
public long TenantTemplateParameterID { get; set; }
public long TenantTemplateTypeID { get; set; }
// rows removed
public virtual TenantTemplate TenantTemplate { get; set; }
}
Anyone knows some overround? Thanks...
I'm pretty sure this is caused by the following EF Core 3.0 breaking change - The foreign key property convention no longer matches same name as the principal property.
According to that rule, TenantTemplateTypeID in TenantTemplateParameter is not considered as FK name.
The weird thing is that at the same time it is the default conventional FK name according to the rules explained in Foreign key shadow properties:
The property will be named <navigation property name><principal key property name> (the navigation on the dependent entity, which points to the principal entity, is used for the naming). If the principal key property name includes the name of the navigation property, then the name will just be <principal key property name>. If there is no navigation property on the dependent entity, then the principal type name is used in its place.
Since the name is already reserved by the "non FK" property, conventional name builder adds index to the default conventional name, hence the observed behavior.
I would consider this as bug/defect of the current EF Core implementation. The workaround/solution of course is to explicitly map the FK property, e.g.
entity.HasMany(e => e.TenantTemplateParameters)
.WithOne(e => e.TenantTemplate)
.HasForeignKey(e => e.TenantTemplateTypeID) // <--
.HasConstraintName("FK_TenantTemplate_TenantTemplateParameters")
.OnDelete(DeleteBehavior.Restrict);
and similar for the other relationship (with TenantTemplateStyle) if it's using the same naming convention.

Scaffold-DbContext returns System.ArgumentNullException: Parameter name: proposedIdentifier in EFCore 2.0 when trying to pluralize

When I run command Scaffold-DbContext "Server=localhost;Database=MyDatabase;Integrated Security=true" Microsoft.EntityFrameworkCore.SqlServer
I get an error:
System.ArgumentNullException: Value cannot be null.
Parameter name: proposedIdentifier
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpUtilities.Uniquifier(String proposedIdentifier, ICollection`1 existingIdentifiers)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpUtilities.GenerateCSharpIdentifier(String identifier, ICollection`1 existingIdentifiers, Func`2 singularizePluralizer, Func`3 uniquifier)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpUtilities.GenerateCSharpIdentifier(String identifier, ICollection`1 existingIdentifiers, Func`2 singularizePluralizer)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpNamer`1.GetName(T item)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.CSharpUniqueNamer`1.GetName(T item)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.GetEntityTypeName(DatabaseTable table)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitTable(ModelBuilder modelBuilder, DatabaseTable table)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitTables(ModelBuilder modelBuilder, ICollection`1 tables)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.VisitDatabaseModel(ModelBuilder modelBuilder, DatabaseModel databaseModel)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.CreateFromDatabaseModel(DatabaseModel databaseModel, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.RelationalScaffoldingModelFactory.Create(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ModelScaffolder.Generate(String connectionString, IEnumerable`1 tables, IEnumerable`1 schemas, String projectPath, String outputPath, String rootNamespace, String contextName, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldContext(String provider, String connectionString, String outputDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl(String provider, String connectionString, String outputDir, String dbContextClassName, IEnumerable`1 schemaFilters, IEnumerable`1 tableFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Value cannot be null.
Parameter name: proposedIdentifier.
In my startup project I have:
public class CustomPluralizerDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection services)
{
services.AddSingleton<IPluralizer, HumanizerToIPluralizerAdapter>();
}
}
public class HumanizerToIPluralizerAdapter : IPluralizer
{
public string Pluralize(string name) => name.Pluralize();
public string Singularize(string name) => name.Singularize();
}
when I remove this code, the scaffolding works.
Dependencies:
DataAccess Project (.NET Standard 2.0)
Microsoft.EntityFrameworkCore.SqlServer 2.0
Microsoft.EntityFrameworkCore.Tools
Microsoft.VisualStudio.Web.CodeGeneration.Design
Startup Project (.NET CORE 2.0)
Microsoft.AspNetCore.All
Looks like a bug in your IPluralizer implementation. Ensure it's not returning null or an empty string for some values.

Timeout when setting up Entity Framework connecting to Azure

I have an Azure database and am setting up Entity Framework. I think the connection string is correct...
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<add name="MyContext" connectionString="Server=tcp:azure_server_name.database.windows.net,1433;Database=azure_database_name;User ID=azure_user_account#azure_server_name;Password=azure_password;Trusted_Connection=False;Encrypt=True;Connection Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
...but I keep getting the following timeout error.
"Message":"An error has occurred.",
"ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":null,
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.",
"ExceptionType":"System.Data.SqlClient.SqlException",
"StackTrace":"
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)\r\n
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)\r\n at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()\r\n
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)\r\n
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)\r\n
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass1a.<CreateDatabaseFromScript>b__19(DbConnection conn)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()\r\n
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()\r\n
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action`1 act)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)\r\n
at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)\r\n
at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)\r\n
at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()\r\n
at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)\r\n
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)\r\n
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)\r\n
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)\r\n
at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)\r\n
at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)\r\n
at System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)\r\n
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()\r\n
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)\r\n
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()\r\n
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)\r\n
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)\r\n
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)\r\n
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()\r\n
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n
at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()\r\n
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator()\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n
at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
"InnerException":{
"Message":"An error has occurred.",
"ExceptionMessage":"The wait operation timed out",
"ExceptionType":"System.ComponentModel.Win32Exception",
"StackTrace":null
}}}
**Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.**
I do have the Azure Firewall open for my IP address...and I'm running this through the debugger.
Here's the little bit of code it should be executing...
public class MyContextInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
context.Database.CommandTimeout = 0;
var books = new List<Book>
{
new Book() {Name = "War and Pease", Author = "Tolstoy",Price=19.95m },
new Book() {Name = "As I Lay Dying", Author = "Faulkner",Price=99.95m },
new Book() {Name = "Harry Potter 1", Author = "J.K. Rowling",Price=19.95m },
new Book() {Name = "Pro Win 8", Author = "Liberty",Price=49.95m },
new Book() {Name = "Book one", Author = "Author1",Price=10.95m },
new Book() {Name = "Book two", Author = "Author2",Price=20.95m },
new Book() {Name = "Book three", Author = "Author3",Price=30.95m }
};
books.ForEach(b => context.Books.Add(b));
context.SaveChanges();
base.Seed(context);
}
}
-----------------Adding book structure and MyContext upon request-------------------
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
public class MyContext : DbContext
{
public MyContext() : base("name=MyContext")
{
}
public DbSet<Book> Books { get; set; }
}
Short Answer
It takes about 120 seconds for SQL Azure to create a database. That is why you are timing out. So, increase the CommandTimeout. One way is to drop a single line of code into your DbContext constructor.
public MyContext() : base("name=MyContext")
{
// three minute command timeout
this.Database.CommandTimeout = 180;
}
Troubleshooting Steps
I just recreated the exception using a brand new SQL Azure server in West US. When I turned on Entity Framework logging, the output showed that the Create database statement caused the timeout. Here is the log output.
Opened connection at 9/8/2015 9:24:14 AM -07:00
select cast(serverproperty('EngineEdition') as int)
-- Executing at 9/8/2015 9:24:14 AM -07:00
-- Completed in 40 ms with result: SqlDataReader
Closed connection at 9/8/2015 9:24:14 AM -07:00
Opened connection at 9/8/2015 9:24:15 AM -07:00
IF db_id(N'mvp1') IS NOT NULL SELECT 1 ELSE SELECT Count(*) FROM sys.databases WHERE [name]=N'mvp1'
-- Executing at 9/8/2015 9:24:15 AM -07:00
-- Completed in 306 ms with result: 1
Closed connection at 9/8/2015 9:24:15 AM -07:00
Opened connection at 9/8/2015 9:24:15 AM -07:00
drop database [mvp1]
-- Executing at 9/8/2015 9:24:15 AM -07:00
-- Completed in 10635 ms with result: -1
Closed connection at 9/8/2015 9:24:26 AM -07:00
Opened connection at 9/8/2015 9:24:26 AM -07:00
create database [mvp1]
-- Executing at 9/8/2015 9:24:26 AM -07:00
-- Failed in 30050 ms with error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Closed connection at 9/8/2015 9:24:56 AM -07:00
To troubleshoot further, I connected to the SQL Azure database with SQL Server Management Studio and ran the log output. The commands succeeded but took 1:53 to complete (just about two minutes). That exceeds the default DbContext command timeout.
The fix: increase the DbContext command timeout to exceed that duration. Bingo. It worked.
Working Console App on My Computer
packages.config
The only package is EntityFramework version 6.1.3.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.3" targetFramework="net452" />
</packages>
App.config
This config uses the interceptors section to log the generated T-SQL. That enabled me to run the logged T-SQL on SQL Server Management Studio to determine how long it takes to create the database.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="MyContext"
connectionString="Server=tcp:d01kzjctcf.database.windows.net,1433;Database=mvp1;User ID=mvp#d01kzjctcf;Password=3pN*iV55XmtW;Trusted_Connection=False;Encrypt=True;Connection Timeout=120;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="C:\Temp\LogOutput.txt"/>
</parameters>
</interceptor>
</interceptors>
</entityFramework>
</configuration>
Program.cs
The demo simply drops and creates the database, seeds it with books, selects all the books, and outputs the number of books to the console.
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
public class Program
{
public static void Main()
{
Database.SetInitializer<MyContext>(new MyContextInitializer());
var count = 0;
using (var context = new MyContext())
{
count = context.Books.CountAsync().Result;
}
Console.WriteLine(string.Format("There are {0} books.", count));
Console.ReadLine();
}
}
public class MyContextInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
context.Database.CommandTimeout = 0;
var books = new List<Book>
{
new Book() {Name = "War and Pease", Author = "Tolstoy",Price=19.95m },
new Book() {Name = "As I Lay Dying", Author = "Faulkner",Price=99.95m },
new Book() {Name = "Harry Potter 1", Author = "J.K. Rowling",Price=19.95m },
new Book() {Name = "Pro Win 8", Author = "Liberty",Price=49.95m },
new Book() {Name = "Book one", Author = "Author1",Price=10.95m },
new Book() {Name = "Book two", Author = "Author2",Price=20.95m },
new Book() {Name = "Book three", Author = "Author3",Price=30.95m }
};
books.ForEach(b => context.Books.Add(b));
context.SaveChanges();
base.Seed(context);
}
}
public class MyContext : DbContext
{
public MyContext() : base("name=MyContext")
{
this.Database.CommandTimeout = 180;
}
public DbSet<Book> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
See Also
Set database timeout in Entity Framework
How do I view the SQL generated by the Entity Framework?
Closing Thoughts
A global CommandTimeout of three minutes is probably appropriate only for development. In production, you will probably want to decrease that or to set it only for certain specific long-running commands such as database creation.

Entity Framework foreign key code first migration error

I've got an entity framework class with two a reference back to another object
public class Review
{
[Key]
public int Id
{get;set;}
public int? FeatureId {get;set;}
public Feature Feature {get;set;}
}
public class Feature
{
[Key]
public int Id
{get;set;}
public ICollection<Review> Reviews {get;set;}
}
This works fine when I generate a migration using Add-Migration
Now, I added a second entry
public class Review
{
[Key]
public int Id
{get;set;}
public int? FeatureId {get;set;}
public Feature Feature {get;set;}
public int? CompareToFeatureId {get;set;}
public Feature CompareToFeature {get;set;}
}
When I run the migration, it does some weird stuff, like renaming the original column.
RenameColumn(table: "dbo.Reviews", name: "FeatureId", newName: "Feature_Id");
AddColumn("dbo.Reviews", "CompareToFeatureId", c => c.Int());
AddForeignKey("dbo.Reviews", "FeatureId", "dbo.Features", "Id");
AddForeignKey("dbo.Reviews", "CompareToFeatureId", "dbo.Features", "Id");
CreateIndex("dbo.Reviews", "FeatureId");
CreateIndex("dbo.Reviews", "CompareToFeatureId");
That would be fine, but the migration fails when i run update-database
Applying code-based migrations: [201211092218271_Test2].
Applying code-based migration: 201211092218271_Test2.
System.Data.SqlClient.SqlException (0x80131904): Foreign key 'FK_dbo.Reviews_dbo.Features_FeatureId' references invalid column 'FeatureId' in referencing table 'Reviews'.
Could not create constraint. See previous errors.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 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)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
ClientConnectionId:f1573dba-4658-462f-969a-9afbf1e4374a
Foreign key 'FK_dbo.Reviews_dbo.Features_FeatureId' references invalid column 'FeatureId' in referencing table 'Reviews'.
Could not create constraint. See previous errors.
Not sure what to do here. Any suggestions?
since you are not following the convention (Feature_ID) you need to help it a bit: on the FeatureId property put an attribute [ForeignKey("Feature")]
[ForeignKey("Feature")]
public int? FeatureId { get; set; }
public Feature Feature { get; set; }