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.
Related
I've have an Asp.Net MVC app in one project and I moved my db context file used to connect to Entity Framework into it's own project, so that I can access EF from both my Asp.Net MVC app and my Azure Function apps. But running the Azure Function throws an exception when trying to get the connection string.
No connection string named 'YogaBandyDatabase' could be found in the application config file.
I tried putting the connection string into the app.config file for the .DataLayer project and I tried putting the connection string into the local.settings.json file and I tried putting the connection string into the portal under application settings connection strings but I'm still getting this exception.
QUESTION - where is it looking for the connection string, it says the application config file? Which one? the one from the .DataLayer project? Did I put it in correctly to the app.config file?
Here is my project structure
Here is the error in the context file
Here is my context file in the .DataLayer project
namespace YogaBandy2017.Context
{
public class YogabandyContext : IdentityDbContext<ApplicationUser>
{
public YogabandyContext()
: base("name=YogaBandyDatabase")
{
}
public YogabandyContext(string connectionString)
: base(connectionString)
{
}
public static YogabandyContext Create()
{
return new YogabandyContext();
}
public DbSet<YogaBandyError> YogaBandyErrors { get; set; }
public DbSet<YogaProfile> YogaProfiles { get; set; }
public DbSet<YogaClass> YogaClasses { get; set; }
public DbSet<YogaSpaceEvent> YogaSpaceEvents { get; set; }
public DbSet<ReportImage> ReportImages { get; set; }
public DbSet<ReportProfile> ReportProfiles { get; set; }
public DbSet<ReportSpace> ReportSpaces { get; set; }
public DbSet<YogaSpace> YogaSpaces { get; set; }
public DbSet<YogaSpaceFollower> YogaSpaceFollower { get; set; }
public DbSet<YogaProfileFollower> YogaProfileFollower { get; set; }
public DbSet<RegisteredStudent> RegisteredStudents { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
}
}
Here is the local.settings.json file with the connection string (maybe syntax is incorrect)
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "the string",
"AzureWebJobsDashboard": "",
"yogabandy2017_RootManageSharedAccessKey_SERVICEBUS": "the string"
},
"ConnectionStrings": {
"YogaBandyDatabase": "the string"
}
}
Here is the connection string in the app.config file for the .DataLayer project
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<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="YogaBandyDatabase" connectionString="my string" providerName="System.Data.SqlClient" />
<add name="YogaBandyErrorDatabase" connectionString="my string" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
This one is a little tricky. Log into the Azure portal and navigate to your Function. Click on the Application Settings link on the Overview tab for your Function. Place your EF connection string under the Connection Strings section.
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.
I am following this tutorial, using Visual Studio Community 2015 v 14.0.25431.01 Update 3 and MS .NET Framework v 4.6.91586, but get the following error when I attempt to scaffold the controller, as described:
I have tried all the suggested solutions here and here, but to no avail. Yes, also tried (re)building the project.
Here is the relevant code from my project.
Student Model:
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
}
SchoolContext:
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().ToTable("Course");
modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
modelBuilder.Entity<Student>().ToTable("Student");
}
}
Added the SchoolContext to the services in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
And this is my connectionstring in appSetting.json:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-ContosoUniversity-75b88406-9d10-4237-814a-3f725b9b4e3d;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Okay, so I've managed to get over the problem of not having a parameterless constructor. As suggested here, I simply provided the constructors to both the DBContext class as well as the Model class as such:
public Student() { }
Now I'm getting a different error. I guess I need to pose it as a new question. I will, but for what it's worth, this is part of the error log:
Attempting to figure out the EntityFramework metadata for the model and DbContext: Student
Exception has been thrown by the target of an invocation. StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkServices.TryCreateContextUsingAppCode(Type dbContextType, ModelType startupType)
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.) StackTrace:
...
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
There is no entity type Student on DbContext ContosoUniversity.Data.SchoolContext at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject,...
I'm trying to run EF6 Code First with SQLite (version 3.11) in Ubuntu/Mono.
Program.cs:
static void Main(string[] args)
{
var db = new Context();
var user = new User() { Nome = "Teste"};
db.User.Add(user);
db.SaveChanges();
}
Context.cs:
public class Context : DbContext
{
public Context():base("Context")
{
Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<Context>());
}
public DbSet<User> User { get; set; }
}
User.cs:
[Table("User")]
public class User
{
[Key]
public int Id { get; set; }
public string Nome { get; set; }
}
Whenever it gets to db.SaveChanges(), it throws the following exception:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SQLite.SQLiteException: SQL logic error or missing database
no such function: last_rows_affected
at System.Data.SQLite.SQLite3.Prepare (System.Data.SQLite.SQLiteConnection cnn, System.String strSql, System.Data.SQLite.SQLiteStatement previous, System.UInt32 timeoutMS, System.String& strRemain) [0x0051b] in <2502d764dcbe41f1ad84e79b77538a55>:0
at System.Data.SQLite.SQLiteCommand.BuildNextCommand () [0x0007c] in <2502d764dcbe41f1ad84e79b77538a55>:0
--- End of inner exception stack trace ---
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update () [0x00080] in <ba0120930fe443a3b992bc3dba4c985a>:0
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2 (System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator ut) [0x00000] in <ba0120930fe443a3b992bc3dba4c985a>:0
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T] (T noChangesResult, System.Func`2[T,TResult] updateFunction) [0x00063] in <ba0120930fe443a3b992bc3dba4c985a>:0
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update () [0x00000] in <ba0120930fe443a3b992bc3dba4c985a>:0
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__d () [0x00000] in <ba0120930fe443a3b992bc3dba4c985a>:0
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T] (System.Func`1[TResult] func, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, System.Boolean startLocalTransaction, System.Boolean releaseConnectionOnSuccess) [0x00064] in <ba0120930fe443a3b992bc3dba4c985a>:0
--- End of inner exception stack trace ---
Does anyone know why this is happening?
UPDATE
I managed to find out what was going on. It looks like that the database created was read-only. All I had to do was change its permissions and it worked!
We managed to solve the problem!
What we did was download the full source of SQLite (sqlite-netFx-full-source-1.0.104.0.zip)and them recompiled SQLite.csproj and EF6.csproj to not use InteropDll using the following commands and specified their platform:
xbuild /p:Configuration=Release /p:UseInteropDll=false /p:UseSqliteStandard=true System.Data.SQLite/System.Data.SQLite.2010.csproj
xbuild /p:Configuration=Release System.Data.SQLite.Linq/System.Data.SQLite.EF6.2010.csproj /p:Platform=x64
And included both dlls in the project, along with Entity's dll.
Then we updated the app.config:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="Context" connectionString="data source=teste.s3db;" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6, Version=1.0.104.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
</DbProviderFactories>
</system.data>
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6, Version=1.0.104.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
</providers>
</entityFramework>
</configuration>
Getting the following errors:
"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." at line 89 of Configuration.cs
Line 89 is simply a context.SaveChanges();, at the end of the class file:
namespace Model.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Model.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ApplicationDbContext context)
{
SeedData.AdditionalSeed _AdditionalSeed = new SeedData.AdditionalSeed();
_AdditionalSeed.Seed_StateOrProvince(context);
_AdditionalSeed.Seed_CountryOrRegion(context);
_AdditionalSeed.Seed_ContactTypes(context);
_AdditionalSeed.Seed_CurrencyCodes(context);
_AdditionalSeed.Seed_Preferences_CalendarSettings_CalendarView(context);
_AdditionalSeed.Seed_Preferences_CalendarSettings_WeeklyView(context);
_AdditionalSeed.Seed_Preferences_CalendarSettings_WhatToShow(context);
_AdditionalSeed.Seed_Preferences_Calendar_FuturePastSettings(context);
_AdditionalSeed.Seed_Preferences_ItemsAndInventory_AdvancedInventory_Barcodes_CopyBarcodeFrom(context);
_AdditionalSeed.Seed_Preferences_ItemsAndInventory_UnitOfMeasureType(context);
_AdditionalSeed.Seed_Preferences_PayrollEmployees_EmployeeDefaults_PayFrequency(context);
_AdditionalSeed.Seed_Preferences_PayrollEmployees_EmployeeDefaults_SickAndVacationDefaults_AccuralPeriod(context);
_AdditionalSeed.Seed_Preferences_PayrollEmployees_EmployeeDefaults_Taxes_FilingStatus(context);
_AdditionalSeed.Seed_Preferences_ReportsAndGraphs_ReportPreferences_DatePreparedFormat(context);
_AdditionalSeed.Seed_Preferences_ReportsAndGraphs_ReportPreferences_PageNumberFormat(context);
_AdditionalSeed.Seed_Preferences_ReportsAndGraphs_ReportPreferences_PageLayout(context);
_AdditionalSeed.Seed_Preferences_SalesAndCustomers_InvoicePackingSlip(context);
_AdditionalSeed.Seed_Preferences_SalesAndCustomers_RoundingRules(context);
_AdditionalSeed.Seed_Preferences_SalesAndCustomers_Shippers(context);
_AdditionalSeed.Seed_Preferences_SalesTax_Intervals(context);
_AdditionalSeed.Seed_Preferences_SalesTax_SalesTaxCode(context);
_AdditionalSeed.Seed_Preferences_SendForms_SendMethod(context);
_AdditionalSeed.Seed_Preferences_SendForms_DeliveryMethod(context);
_AdditionalSeed.Seed_Preferences_SendForms_EmailTemplateCategoryList(context);
_AdditionalSeed.Seed_Preferences_TimeAndExpenses_WorkWeek(context);
_AdditionalSeed.Seed_Security_RoleMaster(context);
context.SaveChanges();
_AdditionalSeed.Seed_Security_AccountingRole(context);
_AdditionalSeed.Seed_Security_BankingRole(context);
_AdditionalSeed.Seed_Security_CentersRole(context);
_AdditionalSeed.Seed_Security_CompanyRole(context);
_AdditionalSeed.Seed_Security_CustomerAndReceivablesRole(context);
_AdditionalSeed.Seed_Security_EmployeesAndPayrollRole(context);
_AdditionalSeed.Seed_Security_FileRole(context);
_AdditionalSeed.Seed_Security_ListsRole(context);
_AdditionalSeed.Seed_Security_ReportsRole(context);
_AdditionalSeed.Seed_Security_SiteSettingsRole(context);
_AdditionalSeed.Seed_Security_TimeTrackingRole(context);
_AdditionalSeed.Seed_Security_VendorsAndPayablesRole(context);
_AdditionalSeed.Seed_TaxesFilingStatus(context);
_AdditionalSeed.Seed_EmploymentType(context);
_AdditionalSeed.Seed_EmployeeEmergencyContactType(context);
_AdditionalSeed.Seed_EmployeeEthnicity(context);
_AdditionalSeed.Seed_EmployeeMaritalStatus(context);
_AdditionalSeed.Seed_Salutations(context);
_AdditionalSeed.Seed_DefaultUnitUsedForTypes(context);
_AdditionalSeed.Seed_UnitOfMeasureDefaultType(context);
context.SaveChanges();
_AdditionalSeed.Seed_UnitOfMeasureDefaultBaseUnits(context);
context.SaveChanges();
_AdditionalSeed.Seed_UnitOfMeasureDefaultRelatedUnits(context);
context.SaveChanges();
_AdditionalSeed.Seed_Terms(context);
_AdditionalSeed.Seed_TaxForms(context);
context.SaveChanges();
_AdditionalSeed.Seed_TaxFormDetail(context);
_AdditionalSeed.Seed_AccountTypes(context);
context.SaveChanges();
_AdditionalSeed.Seed_Industries(context);
context.SaveChanges();
_AdditionalSeed.Seed_OrganizationTypes(context);
context.SaveChanges();
}
}
}
When I comment this line out I then get the following error:
"Sequence contains more than one element" at line 12 of TaxFormDetail.cs
The code for this class file is over 1200 lines so I will only supply the unique lines:
namespace Model.Migrations.SeedData
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
public partial class AdditionalSeed
{
public void Seed_TaxFormDetail(ApplicationDbContext context)
{
context.TaxFormDetail.AddOrUpdate(
r => new { r.TaxFormID, r.TaxCodeLineDescription },
new TaxFormDetailModel() { TaxCodeLineNumber = null, TaxCodeLineDescription = "Schedule F: Interest expense, mortgage", TaxFormID = context.TaxForms.FirstOrDefault(r => r.TaxForm.Equals("1040")).RecordID },
.....
new TaxFormDetailModel() { TaxCodeLineNumber = null, TaxCodeLineDescription = "Pt I-Unrel Bus Inc: Sch C, L3-Inc-real/pers prop", TaxFormID = context.TaxForms.FirstOrDefault(r => r.TaxForm.Equals("990-T")).RecordID }
);
}
}
}
My model for this table is as follows:
[Table(name: "TaxFormDetail")]
public class TaxFormDetailModel
{
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RecordID { get; set; }
public Guid TaxFormID { get; set; }
public string TaxCodeLineNumber { get; set; }
[MaxLength(255)]
public string TaxCodeLineDescription { get; set; }
}
I have read numerous google and SO results on these errors and nothing helps unless I have missed something.
EDIT
The only error I have is the stack trace as this is run by the Package Manager, There is no other way I know of of getting anything else:
System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](DbSet`1 set, IEnumerable`1 identifyingProperties, InternalSet`1 internalSet, TEntity[] entities)
at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, Expression`1 identifierExpression, TEntity[] entities)
at Model.Migrations.SeedData.AdditionalSeed.Seed_TaxFormDetail(ApplicationDbContext context) in Z:\_Profile Storage\Projects\Corporate.WEB\Model\Migrations\SeedData\TaxFormDetail.cs:line 12
at Model.Migrations.Configuration.Seed(ApplicationDbContext context) in Z:\_Profile Storage\Projects\Corporate.WEB\Model\Migrations\Configuration.cs:line 81
at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
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.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
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.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one element
I figured out a workaround for this situation.
For the "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." at line 89 of Configuration.cs error, I changed the seed method to check for existing data for that specific table (tax code) and if the table was empty, add records NOT add or update.
As far as "Sequence contains more than one element" at line 12 of TaxFormDetail.cs goes, I basically did the same thing.
Now every time I do an Update-Database PM command, I do not get any more errors.