Entity framework error when enable migrations - c#

I already had a database first ASP MVC project. Now I remove .edmx file and and all every thing related to database first and make it code first. When I want to Enable-Migrations I get this error in powershell. :
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
Here is my Connection string in webconfig:
<connectionStrings>
<add name="Context" connectionString="Data Source=.\;AttachDbFilename=|DataDirectory|\myDbName.mdf;Initial Catalog=myDbName;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
And Here is my Context :
public class Context : DbContext
{
public Context()
: base("name=Context")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
How can I resolve this problem?

Related

Avoid Oracle schema name with Entity Framework

I'm using the Official Oracle SQL and Entity Framework driver to read the database. But when reading the database it prefixes the table name with "dbo".:
SELECT
*
FROM "dbo"."Woningen"
Without the "dbo". prefix the code works fine, with, it causes the error "table or view does not exist". This is probably because the user isn't 'dbo', so it does not have access to that schema. This is the Entity Framework code that I'm using:
[Table("Woningen")]
public class Woningen
I've tried updating the Oracle nuget package but then it comes up with the error "Connection string is not well-formed". So it probably has the same error as before, it just failed sooner. This is the connectionString format I used:
<add name="DefaultConnection"
providerName="Oracle.ManagedDataAccess.Client"
connectionString="USER ID=testUser;PASSWORD=password;
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=serverUrl)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=Database)));"/>
I can see three possible solutions to this problem, but have no idea how to implement them:
Manipulate Entity Framework to exclude schema names from queries
Give my user access to the schema
Update the driver and fix the connectionstring format, if anyone knows how the format changed..
Note that current code already works in production so the current version should be fine. The database and it's user are new, so the problem could be with how they are created.
You can specify the schema that Entity Framework uses. See below
If you are using Entity Framework 6+ you can use the following
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Set a default schema for ALL tables
modelBuilder.HasDefaultSchema("YourSchemaName");
}
}
If you wish to set a schema on a specific table...
[Table("Woningen"), Schema = "YourSchemaName")]
public class Woningen { }
If you are using EF5
public class Context : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Unfortunately you have to specify each table you want to set a schema for...
modelBuilder.Entity<Woningen>().ToTable("Woningen", "YourSchemaName");
}
}

The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development

I m trying to migrate a project initially developed using EF4 to EF6, to take advantage of EF6 transactions management.
The problem I m facing is that the project has been created using the Database First approach, so when I m using code like context.Database.UseTransaction, I m encountering the following error:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.
This exception triggers inside the OnModelCreating method of my DbContext class.
Any idea ?
Thanks
EDIT:
The thing is that it's legacy code using EDMX with database first approach. I have to implement EF6 transactions inside this project, so it should now be more like a code first pattern.
In addition, here's the context class:
public class MyContext : BaseDbContext
{
public MyContext (DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
}
And the connection string:
<add name="CS"
connectionString="Data Source=MyServ;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework;Enlist=false"
providerName="System.Data.EntityClient" />
I tried setting the providerName to System.Data.SqlClient but it doesn't change anything.
Please note that the original connection string was in the database first format:
<add name="OrderManagement"
connectionString="metadata=res://*/MyManagementModel.csdl|res://*/MyManagementModel.ssdl|res://*/MyManagementModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
providerName="System.Data.EntityClient" />
If I try to open a connection whilst I keep the connection string in the database first format, I m facing the exception Keyword metadata not supported, and when I put the connection string on the code first format, I m facing the error The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.
The most common mistake when converting context from database-first to code first is forgetting to remove the generated OnModelCreating. In a database-first context, OnModelCreating throws the exception:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException(); // ← throws exception
}
So take a look at your context or its base class (and their partial classes) and if it's like above code, you should remove it.
Also your code and configurations need some changes.
You are using providerName="System.Data.EntityClient" for a code first context. You should change the connection string to something like this:
<add name="MyContext" connectionString="data source=server;
initial catalog=database;User Id=user;Password=password;
multipleactiveresultsets=True;application name=EntityFramework"
providerName="System.Data.SqlClient" />
Then you should change your context constructor to something like this:
public partial class MyContext: DbContext
{
public MyContext() : base("name=MyContext") { /* . . .*/ }
// . . .
}
Also if you want to have a common base class, follow above instructions.
Note: To create code-first from an existing database, you can right click on project and choose Add New Item, then under Visual C# under Data select ADO.NET Entity Data Model and click on Add. Then from the Entity Data Model Wizard choose Code First from Database and follow the wizard. For more information see Entity Framework Code First to an Existing Database
You Have to Just Copy Connection String from App.config and Paste it into your Web.config file.
Make Sure your EDMX has updated to latest connection with database.
This works for me.
I just connection string in web.config like this
connectionString="metadata=res:///Models.wimEntities.csdl|res:///Models.wimEntities.ssdl|res://*/Models.wimEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=DATABASE;persist security info=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"

Application can't scaffold items

I created an MVC 5 application in VS 2013 Professional and then used EF 6.1 code first with an existing DB on SQL Server Express. When I try to create the views I’m using the “New scaffolded item…” then selecting the “MVC 5 controller with views, using Entity Framework.” I select the model and context classes and click OK. Then the following error message appears and no code is created. I’ve uninstalled EF Power Tools with the same error.
Error
There was an error running the selected code generator: ‘Exception has
been thrown by the target of an invocation.’
I've also tried uninstalling/reinstalling VS 2013 and SQL Server with no changes.
Any other ideas about what might cause this error?
In my case I moved my connection strings out of the Web.config to
<connectionStrings configSource="ConnectionStrings.config"/>
that when I started getting the error when I was trying to scaffold.
There was an error running the selected code generator: ‘Exception has been thrown by the target of an invocation.’
Moving my connection strings back to the Web.config solved my issue.
I had this problem too,
I solved the problem by calling the base.onModelCreating in my DB context
base.OnModelCreating(modelBuilder);
I had faced the same problem while creating controller using scaffold with 'ASP.NET MVC5 using views with Entity Framework'
The problem was because I provided <connectionStrings> tag before <configSections> in web.config. setting <connectionStrings> after <configSections> resolved the issue.
I guess, while scaffolding, ASP.NET MVC want to resolve the Entity Framework first, then the connection string, as I have provided connection string earlier so that after resolving the Entity Framework version it could not find the connection string so it thrown invocation problem.
This solved the issue for me,
Adding throwIfV1Schema: false to base of DbContext
As so:
public MyDbContext() : base("ConectionStringName", throwIfV1Schema: false) { }
Late reply; but, I am posting this answers with the hope that somebody can use this answer to solve their problem.
For some reason, if your program CANNOT read connectionString information (either from web.config or from other means) then, this error will be thrown.
Make sure that valid connectionString information is being retrieved properly without any problem.
I had the same error message.
I tried adding a new Data context class from the Add Controller dialog, and then I got a different error:
There was an error running the selected code generator:
'Sections must only appear once per config file. See the help topic
<locations> for exceptions.
It turns out that I had two <connectionStrings> elements in my web.config file. (I had pasted one from the app.config of the class library that contained my Entity Framework model.)
In my case, I had to revert my DBContext constructor to just using a static connection string, as defined in web.config
Scaffolding did not work when I used a dynamically created connection string.
public MyContext() : base("name=MyContext") { }
I had the same problem where it wouldn't add scaffold items it seems that uninstalling entity-framework through the nuget package manager console works
To Run Package Manager Console :
Tools -> NuGet Package Manager -> Package Manager Console
To Remove:
UnInstall-Package EntityFramework
To Reinstall:
Install-Package EntityFramework
Or in one command:
Update-Package -reinstall EntityFramework
I hope this can help someone as it took me a while to come to this.
This may help resolve your error.
In my OnModelCreating i was doing this for each entity:
modelBuilder.Configurations.Add(new EntityTypeConfiguration<EntityModel>);
When i changed it to the following i stopped getting the error you are receiving.
modelBuilder.Entity<EntityModel>();
I tried most of the above without luck.
What finally worked was:
Delete the previously dynamically created string entry
Delete my model (keeping all controllers and views)
Recreate the ADO.NET Entity Data Model - using the same name, creating a new connection string entry with the same name as before
Then everything worked again, minus 3 hours of development time.
re-add (from a backup) all of my property attributes to the table/entity classes
Seems to have something to do with the dynamically created connection string and the model. Would appreciate any thoughts on what could have happened.
In my case, I solved the issue with the connection string in the web.config.
Previuos the issue I has
<connectionStrings configSource="Configs\ConnectionString.config"/>
and I doesnt know why, but vs cant connect to the database and fail.
after the change
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
and it works
My solution was as simple as changing back the connection string name in my Web Config to DefaultConnection. Even though my dbContext has another name!
Took me 2 hours to find out this nonsense!
It seems a problem of connecting setting / inconsistent entry in via Web.config.
To fix this issue , follow below steps:
Remove connection related information (staring with <connectionStrings> from Web.config and remove models generated so far.
Now generate the model and it will add fresh connection entry in Web.config file. Once model is generated, build the solution then start doing Scaffolding controlled. it will work.
I ran into this problem too using VS 2015. I tried all the other solutions here to no success. It turned out that my connection string (although formed exactly how MS tells us to form it) needed double \ to work properly.
Here is what it was that was NOT working:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
and here is what I changed it to in order to get the code generator to work:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
Notice the double \ characters in front of V11.0 and the database name.
Hope this saves somebody else some time.
UPDATE
This gets the code generation to work, but then the app won't run because the \V11.0 isn't a valid connection string. This looks to me like MS has a bug in their code generation when it parses the connection string. I had to change it back to a single \ after I ran the code generation to get the app working again.
UPDATE 2
After some more digging by my partner, we found out that what was really screwing up code generation was the fact that we had changed the "Initial Catalog" field. When the project was created by the Wizard, it automatically set the Initial Catalog to aspnet--. We had then changed this Initial Catalog field to be DB. This worked great for the application running. It could get to the database just fine. But for some reason this screws up the code scaffolding generation. By putting the Initial Catalog back to what it was before (the aspnet--, the scaffolding started to work again (without needing the \V11.0).
Hope that helps somebody in the future.
Check relationships between entities or other model design problem. For testing, create new class model without no relationship and use Scaffold to generate controllers and views.
Works for me.
I was getting the same error when I made some changes to my model .. Only way I was able to resolve was
1) stop/kill the process
2) clean solution and rebuild the solution
If by any chance you are following "Getting Started with Entity Framework 6 Code First using MVC 5" by Tom Dykstra.
I doubled check everything and my connection string is perfect. What I failed to realize was I copied another set of appSettings which I already have. Look below
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
My advice is to check every inch of Web.config and I'm sure that is the culprit.
In my case NuGet added the following provider to the web.config:
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact"/>
When I changed the provider to
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
It solved the problem (costed me about 5 hours though to figure it out :-( )
I Had the same error. Here are the two things I did to fix the problem:
Added name to base in my context:
base("name=connectionstringname")
I made a mistake in myconnection string and fixed it.
It is (I'm 99% positive) a connection string issue. Once i fixed the issue in Web.Config the error went away. I was using DB first, in another project and once I copied the DB first connection string from the App.config into the web.config (using the same name) it worked as expected.
Using Visual Studio 2015
Upgraded mysql server and in the process the mysql for visual studios was upgraded from 6.9.7 to 6.9.8
In my web config there was still a reference to the old 6.9.7 version
Here is my git diff that solved the issue:
- <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.7.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
+ <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.8.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
I realize this question is old now, but I thought I'd post what solved my issue in case it helps anyone later on. In my case, it was a combination of several things mentioned in other answers. To secure my connection string I had...
Moved the connection string out of the Web.config file
Moved the server name and password to a separate file referenced in the AppSettings portion of Web.config
Used a SqlConnectionStringBuilder to put the elements together and then pass it to my context class constructor
After doing this, I was unable to create any more controllers. To fix the issue, I had to ...
Put the complete connection string back in Web.config AND remove the reference to the external connection string file
Add a parameterless constructor to my context class and give it the name of my connectionString like this:
public contextClass() : base("name=connectionStringName") { }
Rebuild the solution, and create the controller again, and it worked!
everyone. I know I'm a little late, but I think that is still valid to share my experience with this problem.
I faced this message in two projects and in both cases the problem was with the connection string.
In the first case it was "InitialCatalog" instead of "Initial Catalog" (separated).
In the second case the server name (Data Source param) was wrong.
I hope it helps.
Best regards.
For some reason when I comment the oracle.manageddataaccess.client section out between <configSections> in web.config, it worked. (VS 2015 and ODT 12)
<configSections>
<section name="entityFramework" type" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!--<section name="oracle.manageddataaccess.client" />-->
</configSections>
In my case, the problem was caused by an external app settings file:
<appSettings configSource="appSettings.config" />
Bringing the app settings back into the web.config file resolved the issue.
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
I had this:
<appSettings configSource="App_Config\Server\AppSettings.config" />
<connectionStrings configSource="bin\Connections.config" />
I had to remove BOTH AND put back.
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
Removing just still caused the same error.
Using: VS 2015 Community Edition and EF 6.1.3
Implemented also: Seed method, with a personalized class, and configured in the web.config file to run every time that the model changes.
This seems to be related to some misconfiguration in the web.config file, in my case, like some of the cases I see in this post with other sections of the file, the section was repeated with different content, but it's repeated the main tag of course. The case of the section out of place, over the section, is also cause of the same behavior and narrow message while try to scaffold.
Your context class might be throwing an exception.
I was following along in the book "C# 6.0 and the .NET 4.6 Framework" and one of the last exercises of the data access layer section was to add logging. Well, I guess that blows up the scaffold wizard. Probably file permissions on sqllog.txt or HttpRuntime is not defined...who knows. When I commented all this stuff out, it worked again.
namespace AutoLotDAL.EF
{
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using AutoLotDAL.Interception;
using AutoLotDAL.Models;
using System;
using System.Data.Entity.Core.Objects;
using System.Web;
public class AutoLotEntities : DbContext
{
//static readonly DatabaseLogger databaseLogger =
// new DatabaseLogger($"{HttpRuntime.AppDomainAppPath}/sqllog.txt", true);
public AutoLotEntities()
: base("name=AutoLotConnection")
{
////DbInterception.Add(new ConsoleWriterInterceptor());
//databaseLogger.StartLogging();
//DbInterception.Add(databaseLogger);
//// Interceptor code
//var context = (this as IObjectContextAdapter).ObjectContext;
//context.ObjectMaterialized += OnObjectMaterialized;
//context.SavingChanges += OnSavingChanges;
}
//void OnObjectMaterialized(object sender,
// System.Data.Entity.Core.Objects.ObjectMaterializedEventArgs e)
//{
//}
//void OnSavingChanges(object sender, EventArgs eventArgs)
//{
// // Sender is of type ObjectContext. Can get current and original values,
// // and cancel/modify the save operation as desired.
// var context = sender as ObjectContext;
// if (context == null)
// return;
// foreach (ObjectStateEntry item in
// context.ObjectStateManager.GetObjectStateEntries(
// EntityState.Modified | EntityState.Added))
// {
// // Do something important here
// if ((item.Entity as Inventory) != null)
// {
// var entity = (Inventory)item.Entity;
// if (entity.Color == "Red")
// {
// item.RejectPropertyChanges(nameof(entity.Color));
// }
// }
// }
//}
//protected override void Dispose(bool disposing)
//{
// DbInterception.Remove(databaseLogger);
// databaseLogger.StopLogging();
// base.Dispose(disposing);
//}
public virtual DbSet<CreditRisk> CreditRisks { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Inventory> Inventory { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
}
EF 6.1 does not Support scaffolding template use EF 5
Chares

DropCreateDatabaseIfModelChanges EF6 results in System.InvalidOperationException: The model backing the context has changed

After migrating to Entity Framework 6 I get an error when executing unit tests on the build server.
I'm using the DropCreateDatabaseIfModelChanges initializer. When I change it to MigrateDatabaseToLatestVersion everything works, but I want to stick with the former initializer.
The error I'm getting is:
System.InvalidOperationException: System.InvalidOperationException:
The model backing the 'AppContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269)..
Which is correct, it changed, but with DropCreateDatabaseIfModelChanges initializer, it should be recreated. Any ideas?
EF is configured in App.config. Here's the relevant part:
<connectionStrings>
<add name="AppContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=my.app.unittest;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<contexts>
<context type="my.app.core.Data.AppContext, my.app.core">
<databaseInitializer type="System.Data.Entity.DropCreateDatabaseIfModelChanges`1[[my.app.core.Data.AppContext, my.app.core]], EntityFramework" />
</context>
</contexts>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Well, it looks like EF 6.0 introduces a new rule:
"If the DbContext is using an Initializer AND Migrations are configured, throw an exception when building the model".
Up to and including the EF 6 RC this wasn't enforced. The annoying part is that "Migrations are configured" is defined by the implementation of a DbMigrationsConfiguration. There doesn't appear to be a way to programmatically disable Migrations in tests - if you implemented
I worked around it in a way very similar to Sebastian Piu - I had to get rid of the Configuration class from my tests, but I couldn't just remove it because we're using Migrations for our main project. Argh!
This was my code before:
public class MyDbContext : DbDContext, IMyDbContext
{
public IDbSet<Users> Users {get; set;}
public IDbSet<Widgets> Widgets {get; set;}
}
// Migrations are considered configured for MyDbContext because this class implementation exists.
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
// Declaring (and elsewhere registering) this DB initializer of type MyDbContext - but a DbMigrationsConfiguration already exists for that type.
public class TestDatabaseInitializer : DropCreateDatabaseAlways<MyDbContext>
{
protected override void Seed(MyDbContext context) { }
}
I encountered the System.InvalidOperationException when the DbContext was being initialized in my test code. Since the application doesn't use any Initializer, there were no problems running the app as before. This only broke my tests.
The solution (which feels more like a workaround to things missing from EF) is to segment the Initializer and DbMigrationsConfiguration so only one is seen in a runtime environment. I want my tests to use the Initializer and I want my application to use the DbMigrationsConfiguration. This could be done more cleanly if DbContext had an interface, but alas it only implements IObjectContextAdapter.
First I made my DbContext abstract:
public abstract class MyDbContextBase : DbContext, IMyDbContext
{
public IDbSet<Users> Users {get; set;}
public IDbSet<Widgets> Widgets {get; set;}
}
Then I derived 2 classes:
public class MyDbContext : MyDbContextBase
{
public MyDbContext(string connectionStringOrName, IDatabaseInitializer<MyDbContext> dbInitializer)
: base(connectionStringOrName)
{
}
}
public class MyTestDbContext : MyDbContextBase
{
public MyTestDbContext(string connectionStringOrName, IDatabaseInitializer<MyDbContext> dbInitializer)
: base(connectionStringOrName)
{
Database.SetInitializer(dbInitializer);
}
}
Both a MyDbContext and a MyTestDbContext are IMyDbContexts, so your existing dependency injection setup should work without requiring changes. I only tested Spring.NET.
My DbMigrationsConfiguration implements the derived type that is NOT used by tests:
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
Finally, the initializer's type was moved to the derived test class type:
public class TestDatabaseInitializer : DropCreateDatabaseAlways<MyTestDbContext>
{
protected override void Seed(MyTestDbContext context) { }
}
I can confirm my tests are passing and my application (and Migrations) is still working as before.
I found the same issue just after upgrading to EF6. After reading Stefan´s comment and having the same symptoms as he describes (tests were loading the Configuration class from my main project)
Solution/workaround in my case was to
create new class TestContext: MyDataContext in my Tests project
change the initialiser from DropCreateDatabaseAlways<MyDataContext> to DropCreateDatabaseAlways<TestContext>
update/generalise places where I created my real context to use the test one
I could do this because most of my tests just extend from a PersistenceTest class, so I understand this might be a pain to change if you have a big catalog. So looking forward to other solutions
This is throwing because you have migrations enabled and you are using the DropCreateDatabaseIfModelChanges initializer. Entityframework does not support using this initializer with migrations. You have two options:
Disable the initializer
or
Disable migrations by removing the migrations configuration
It looks like this behavior was intended. Here's a quote from one of the developers:
This change of behavior was by design because EF5 would create the database without using the defined migrations meaning that the database created by the initializer could be different to the one created by Migrations. This could lead to testing against one database schema but running in production against a different database schema. However, we have tentatively decided to make a change to this behavior and this is being tracked here: https://entityframework.codeplex.com/workitem/1709
What works fine for me is excluding the migrations using define. Here is how:
Create a new configuration called Test that defines TEST
In your tests, throw an error when TEST is not defined.
Exclude your migrations when TEST is defined:
#if !TEST
internal sealed class Configuration : DbMigrationsConfiguration<Context>
{
//...
}
#endif
You might need to exclude all of your migrations, which isn't totally satisfying either (but I haven't tried it because I don't have any migrations yet).

Code-First change data source without connection string

I seem to have an issue creating an MVC4 application where I have adopted the code-first approach to creating my models but no connection string seems to have been created in the web.config file.
The constructed database seems to have been built on (localhost)\SQLEXPRESS instance but I would like to change this to an external data source. Without a connection string to update I'm not sure how to do this.
Please could someone point me in the right direction?
EDIT: I found the following diagram which highlights what the answers have said pretty well
(source: entityframeworktutorial.net)
You have to add a connection string yourself
<add name="SomeDb" connectionString="Data Source=SERVENAME;Initial Catalog=DBNAME;User Id=loginid;Password=password" providerName="System.Data.SqlClient" />
Name of this string should match to the name of your context class.
public class SomeDb: DbContext
{
public SomeDb()
: base("name=SomeDb")
{
}
}
This should do it.
If you use ADO.NET Entity Framework(.edmx) it will update your web.config file with connection string. but in code-first you need to write your connection string in web.config like,
suppose you dbcontext looks like,
public class SampleDbContext:DbContext
{
public SampleDbContext():base("SampleDbContext")
{
}
...
...
}
after you should create your connection string in web.config with SampleDbContext name like,
Hope this helps
You have to create a connection string with the same name as your DbContext class:
<connectionStrings>
<add name="NameOfDbContext" connectionString="Data Source=ServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
You can also specify the connection string yourself using an overload of the DbContext class:
public class MyDbContext() : base("ProductionDbContext")
{
}
Now you can use ProductionDbContext as connection string.
See this article on MSDN for more information.

Categories

Resources