SQL logic error or missing database no such function: last_rows_affected - entity-framework

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>

Related

Evaluating object with List property

I try to evaluate this rule
<?xml version="1.0" encoding="utf-8"?>
<codeeffects
xmlns="http://codeeffects.com/schemas/rule/41"
xmlns:ui="http://codeeffects.com/schemas/ui/4">
<rule id="PerformCalculation" webrule="5.0.9.6" utc="2020-11-23T13:13:42.3010" type="domain_product.Configs.WorkflowEngine.MicroflowModel, domain-product, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" eval="false">
<definition>
<if>
<clause>
<rule id="40494eaf-4de0-4b3b-85b9-1c73473c2660" operator="doesNotExist">
<property name="e536c617_2636_47e8_93bb_66bb6c7fe3c0" />
</rule>
</clause>
<then>
<set>
<property name="775e6e9c_154f_45b3_9360_3d0a154ee19d" />
<value>test1</value>
</set>
</then>
</if>
</definition>
<format>
<lines />
</format>
</rule>
<rule id="40494eaf-4de0-4b3b-85b9-1c73473c2660" webrule="5.0.9.6" utc="2020-11-23T13:13:42.3010" type="transformify_template_api_factory_product.Domain.Model_cb958c7f_3681_40c5_573c_08d88fb1664f, DynamicAssembly.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" eval="true">
<definition>
<condition type="equal">
<property name="Godini" />
<value type="numeric">50</value>
</condition>
</definition>
<format>
<lines />
</format>
</rule>
</codeeffects>
The classes are
public class Model_710e265b_d07c_4c1b_573d_08d88fb1664f
{
[Field(DisplayName = "Ime")]
public string Ime { get; set; }
[Field(DisplayName = "Prezime")]
public string Prezime { get; set; }
[Field(DisplayName = "Godini")]
public int Godini { get; set; }
}
public class MicroflowModel
{
[Field(DisplayName = "Variables -> Persons")]
public List<Model_710e265b_d07c_4c1b_573d_08d88fb1664f> e536c617_2636_47e8_93bb_66bb6c7fe3c0{ get; set; }
[Field(DisplayName = "Variables -> var1")]
public string 775e6e9c_154f_45b3_9360_3d0a154ee19d { get; set; }
}
The class Model_710e265b_d07c_4c1b_573d_08d88fb1664f is a part of an assembly called 'DynamicAssembly.dll' that is not loaded into the app-domain, but the class exists.
The class MicroflowModel is a part of a dynamically created assembly, and is generated with TypeBuilder.
When evaluating objects without List properties, the evaluation process is ok.
When evaluating objects with lists from the 'DynamicAssembly.dll' assembly (like in the example), the Evaluator constructor fails with this Message:
Value cannot be null. (Parameter 'type')
and StackTrace:
at System.Linq.Expressions.Expression.Validate(Type type, Boolean allowByRef)
at System.Linq.Expressions.Expression.Parameter(Type type, String name)
at CodeEffects.Rule.Core.ExpressionBuilderBase.BuildRule(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.Build(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.BuildIfRule(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.Build(XElement element)
at CodeEffects.Rule.Core.ExpressionBuilderBase.Build(IEnumerable`1 elements)
at CodeEffects.Rule.Core.ExpressionBuilderBase.GetSafeExpressionBody(XElement rule, Boolean addSourceNullCheck)
at CodeEffects.Rule.Core.ExpressionBuilder.GetPredicateExpression(XElement rule)
at CodeEffects.Rule.Core.Evaluator.CompileRule(XElement rule)
at CodeEffects.Rule.Core.EvaluatorBase..ctor(Type sourceType, String rulesetXml, EvaluationParameters parameters, IFlexDataProvider provider)
at CodeEffects.Rule.Core.Evaluator..ctor(Type sourceType, String rulesetXml, EvaluationParameters parameters)
at ...
Please help
You need to make that class available. The ExpressionBuilder must be able to load the type referenced in the internal rule (id="40494eaf-4de0-4b3b-85b9-1c73473c2660") using Type.GetType(), so as to build an expression tree.
Internally it calls
Type ruleType = Type.GetType("transformify_template_api_factory_product.Domain.Model_cb958c7f_3681_40c5_573c_08d88fb1664f, DynamicAssembly.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
Since it can't find it, the result is null and the next call to Expression.Parameter() fails.

Connection string could not be found running azure function and entity framework

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.

Conflict "add-migration" and "update-database" result for entity framework code base migration

I tried to run code base entity framework migration. And I always get this error (except the initial migration) when run "add-migration" command: Unable to generate an explicit migration because the following explicit migrations are pending: [201607141552034_Add_storeId_firstname_to_customer]. Apply the pending explicit migrations before attempting to generate a new explicit migration. However, if I try to run "update-database -Verbose -ConnectionStringName "ZzaDbConnectionString", I get an very confusing/conflict error: No pending explicit migrations. I tried to delete the migration file then use add-migration to create it again. It only work once. The next time (for example, if I want to add a column to my table), I got the same error. Any suggestion why the problem? Thanks.
EDIT: add code and configuration.
This is Entity class.
namespace Zza.Entities
{
public class Customer
{
public Guid Id { get; set; }
[MaxLength(50)]
public string FullName { get; set; }
}
}
This is Context class:
namespace Zza.Data
{
public class ZzaDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
}
This is console class:
namespace TestEFMigration
{
public class Program
{
static void Main(string[] args)
{
CreateDataBase();
}
private static void CreateDataBase()
{
var context = new ZzaDbContext();
context.Database.Initialize(false);
}
}
}
context class's app.config
<add name="ZzaDbConnectionString"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite‌​;MultiSubnetFailover=False"
providerName="System.Data.SqlClient" />
Console's app.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ZzaDbConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Zza;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
iceheart

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.

The type was not mapped

Im trying to run a simple program according to all tutorial I could find.
This is my test code:
Program.cs:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EF5WithMySQLCodeFirst
{
class Program
{
static void Main(string[] args)
{
using(var context = new DatabaseContext())
{
var defaultForum = new Forum { ForumId = 1, Name = "Default", Description="Default forum to test insertion." };
context.Forums.Add(defaultForum);
context.SaveChanges();
}
Console.ReadKey();
}
public class Forum
{
public int ForumId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class DatabaseContext : DbContext
{
public DbSet<Forum> Forums { get; set; }
}
}
}
This is the web.config:
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
When I execute the code, in using(var context = new DatabaseContext()) line, I get the following error:
The type 'EF5WithMySQLCodeFirst.Program+Forum' was not mapped. Check
that the type has not been explicitly excluded by using the Ignore
method or NotMappedAttribute data annotation. Verify that the type was
defined as a class, is not primitive, nested or generic, and does not
inherit from EntityObject.
Please ignore the name MySQL since I am not trying yet to connect it to MySQL but for it
to work with localdb. I searched around and can't get the solution for problem yet.
I think it's failing because your Forum class is nested inside your Program class. Like the error message says, entity types can't be nested. Try moving it outside so that it's a top-level class within the namespace.