Entity Framework Execute Migrations on Test Server - entity-framework

I need to update a test server database when deploying, and I do not find a way to do it.
We are not using automatic migrations, so we do it manually.
Can I execute it on the test server directly? Maybe a console program?
I'm using the NuGet call for local development: Update-Database
I know we can generate the script files, do I have to do it manually?

You can use the MigrateDatabaseToLatestVersion database initializer to execute your migrations either through code or configuration. In code you'd do the following when the application starts:
Database.SetInitializer<MyContext>(
new MigrateDatabaseToLatestVersion<MyContext, MyMigrationConfig>()
);
Or in your app's .config file:
<entityFramework>
<contexts>
<context type="MyContext">
<databaseInitializer
type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[
[MyContext], [MyMigrationConfig]
], EntityFramework" />
</context>
</contexts>
</entityFramework>

If your using Visual Studio, you can use the publish fonction to also execute a script. Look here for more détails:
http://learn.iis.net/page.aspx/1081/building-a-web-deploy-package-from-visual-studio-2010/
If your using team fondation server, you can even automate it:
http://weblogs.asp.net/jdanforth/archive/2010/04/24/package-and-publish-web-sites-with-tfs-2010-build-server.aspx
Also to generate the script maybe you could use migrate.exe (it comes with ef 4.3 I think when getting the nuget package) and run it in a post build évent...

Related

PostgreSQL data provider missing from wizard in Visual Studio 2015

I've spent a day trying to migrate an Entity Framework 6 SQL Server CE to PostgreSQL.
I've copied the database over fine, but I can't seem to get the data provider to work.
Firstly I tried the older 2.2.7 version of the EF provider, which doesn't require .NET 4.5 (because our project can't use it), but that didn't work. I've been using NpgsqlConnection instead of SqlConnectionStringBuilder and changed the app.config to have a connection string with Host (I tried Server but it didn't like it) and Database values, and made sure the EF section is as follows:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
I've now ignored this limitation just to try and get it working, so I have the EF6 v3.1.1 version of the EF provider and the latest .NET provider (v3.2.2) and that's not working either.
In an attempt to fix it, I've also been trying to re-sync the EDMX from the SQL Server CE to the PostgreSQL replacement by installing the VS2015 extension, but it just gave a message saying an error occurred, so I tried this: https://github.com/npgsql/npgsql/issues/1514
which got further, opening the window, but then crashed as soon as I typed into the boxes. Since upgrading the project to .NET 4.5, this provider no longer appears at all...
I've tried reinstalling everything several times and restarting VS a lot, and Since upgrading I've also tried installing the GAC files, as it wasn't clear if the VS extension needed them (also v3.2.2).
Is anyone able to shed some light on how easiest to get all this working, preferably without the requirement of .NET 4.5?
Thanks
I got it working with installing the Visual Studio Extension Npgsql PostgreSQL Integration.
Follow the instruction on this page: https://www.npgsql.org/efcore/
This thread led me to the right path: Add custom data source to visual studio 2015
Installing the npgsql extension as described in tsChan's answer wasn't enough for me, I also had to modify my app.config (I suspect because it was created before I installed the extension) to include the npgsql data provider in the EntityFramework section as follows:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
After I did that, the provider appeared in the wizard options.
PostgreSQL data provider missing from wizard in Visual Studio 2019 //It works
Install this extension "Npgsql PostgreSQL Integration" https://marketplace.visualstudio.com/items?itemName=RojanskyS.NpgsqlPostgreSQLIntegration
install "EntityFramework6.Npgsql" package from Nu get Package manager
After installation without restarting or editing app.config file you will see changes on your project references folder and app.config file
Now click on add->new item->ADO.NET Entity data model->EF designer from database->new connection->change you will see postgress in data source

Migrations and configuration.seed not running on Azure deployment

I am on EF, with a standard code first DbContext.
public class MyContext : DbContext {}
My seed method in Configuration.cs runs fine locally, when I do an 'Update-Database'
But when I deploy to an Azure Web App instance, none of my seed data shows up. My initial migration runs, but when I add a new migration and publish, it does not get run. So basically only my Initial migration is showing up, and no seed data.
If I check 'Update database', the publish just hangs indefinitely.
I have read that there is supposed to be an 'Execute code first migrations' checkbox, but I don't seem to have that checkbox. I have tried cleaning my project, and restarting VS2013update4. Rebuilding the project, etc. Nothing makes it show up. I have also tried this: http://www.dominicstpierre.com/2012/11/enable-code-first-migrations-check-box.html, but it doesn't seem to work with VS2013u4.
Migrations are in my MyProject.DataLayer project. The actual web app is in MyProject.WebApp. Will this matter? It works fine locally.
What can I do to get this checkbox to show up?
Entity Framework sets up an initialiser on the target machine web.config
This initialiser is run when your app hits the database for the first time.
Here is a link to a good article on the asp.net site that explains how to achieve this: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application
I had the same issue, the seed would simply not get executed after an azure deployment.
I fixed this by adding this to the entityFramework element in the web.config:
<entityFramework>
<!-- excluded other settings for brievity... -->
<contexts>
<context type="WebApplication.Data.ApplicationDbContext, WebApplication" disableDatabaseInitialization="false" >
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[WebApplication.Data.ApplicationDbContext, WebApplication], [WebApplication.Migrations.Configuration, WebApplication, Version=1.0.0.0, Culture=neutral]], EntityFramework" />
</context>
</contexts>
</entityFramework>
It is important that the namespaces are correct for ApplicationDbContext and Configuration, otherwise it will not work.

Database first create entity framework 6.1.1 model using system.data.sqlite 1.0.93

I have a project that I just updated using nuget. This updated entity framework from 6.1 to 6.1.1, and it updated sqlite to 1.0.93. I wanted to update my model from my latest database. I did the steps of
1) Model from Database
2) Select sqlite database
3) Generate
After the generation I received the following error message shown below. I have the 1.0.93 design time components install. Does anyone know what exactly is causing this error. The project references and versions all match the versions shown above.
Error Message:
Your project references the latest Entity Framework; however and Entity Framework database provider
compatible with this version could not be found for you data connection.
Update:
I ended up installing 6.1.0 manually using the package manager console
Install-Package EntityFramework -Version 6.1.0
Then in my csporj files replacing
packages\EntityFramework.6.1.1
with
packages\EntityFramework.6.1.0
I tried creating EF Designer from Database and Code First from Database but I am still getting the same error.
UPDATE
I have followed the instructions Tom has provided, and thanks time for taking the time to respond in depth it is appreciated. But I cannot get the entity framework designer to work with SQLite 1.0.93. What I have found:
1) When I add the SQLite data source from the tools menu as Tom describes I see the SQLite data provider.
2) But when I restart visual studio the data source is not connected
3) The data source can be refreshed and it is valid after restart
4) Add new data item but SQLite is not listed as a provider
I have double checked the registry and EF6 is appended to the invariant name, the SQLite dlls are registered in the GAC. I will try to see what else I can find but at this point I am not sure what to look for. As a side note I have tried dotConnect and it does not work either with EF 6.1.1.
Update 2
Does anyone know if the Entity Framework Designer has a logging option to find out what might be happening?
[ UPDATE : for an easier solution that works with Visual Studio 2013 Update 4 (Pro and Ultimate) and recent versions of Sqlite Providers and EF, look at the solution 'broslav' posted below. Don't know if it works with Express editions... ]
Ok, this is a suggestion. This does NOT work for Visual Studio Express editions.
Also, I'm not sure how to get it to work for an update of an existing project.
And it is an absolute pain in the butt.
I haven't tested if everything is required, but this should work:
First, do NOT use the NuGet package for SQLite, but download the assembly installer from here:
http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
Install the Setups for 32-bit Windows (.NET Framework 4.5.1) installer: sqlite-netFx451-setup-bundle-x86-2013-1.0.93.0.exe (10.00 MiB) (NOT the 64-bit version). This is the only one with the designer.
Install and select to install in the GAC and install the Designer for VS13.
For the following, the exact order is important!
I made a video of these steps, see: http://vimeo.com/103372740
Create a project in VS13. Target the build to framework 4.5.1 and x86 explicitly. Save and build.
Next, install the latest EF 6 package (6.1.1) from NuGet. Save and build.
Manually add references to the installed SQLite assemblies (including the Designer) , under the Reference Manager under Assemblies you can find the Extensions option for selecting the four added assemblies in the GAC : System.Data.SQLite Core + Designer + for Entity Framework + for LINQ.. Save and build.
Then create a connection to your database via Connect to Database under Tools. Before you do anything else Save and Build and then RESTART Visual Studio. DO NOT DO ANYTHING ELSE before starting the ADO.NET Entity Data Model wizard, so DO NOT refresh the database connection.
Add an ADO.NET Entity Data Model, select Generate from Database.
Your database connection will show up in the drop-down list. Keep it there, but select to create a New Connection anyway and select the exact same database again (as if you are creating a new connection). It sounds silly, but it is crucial, see image below...
When I actually Added an ADO.NET Entity Data Model this way it did present the annoying error, but the Next button is selectable and everything worked regardless (amazingly)!
Designer works, retrieving data and writing data works.
Haven't tested deployment on another machine though... I'm using Win7 64-bit.
CHANGED UPDATE: To get the correct configuration to actually access the database, you have to install the System.Data.SQLite.EF6 package from NuGet after doing all of the above, then add
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
to the App.Config and remove the other providers and remove everything in between <system.data></system.data>, otherwise you'll get some exception. But note that this means that every time you want to update the EDMX model, you have to change the App.Config invariantName="System.Data.SQLite" to invariantName="System.Data.SQLite.EF6" and vice versa.
** Is this getting ridiculous? Yes, it is! And it gave me quite a headache... **
This is what worked for me:
had Windows 8.1 Pro x64
had VisualStudio 2013 Ultimate Update 4
installed http://system.data.sqlite.org/downloads/1.0.94.0/sqlite-netFx451-setup-bundle-x86-2013-1.0.94.0.exe (in GAC, plus designer)
installed EFTools6.1.2ForVS2013.msi from https://www.microsoft.com/en-us/download/details.aspx?id=40762
in old or new solution/project that targets .NET 4.5.1 and Any CPU installed via NuGet package System.Data.SQLite
added new model from database (I did not see the SQLite provider here until I installed the NuGet package inside the project)
to actually access the data, I had to rearrange the add and remove items inside the DbProviderFactories tag in the app.config
So the packages I had were:
<packages>
<package id="EntityFramework" version="6.1.1" targetFramework="net451" />
<package id="System.Data.SQLite" version="1.0.94.1" targetFramework="net451" />
<package id="System.Data.SQLite.Core" version="1.0.94.0" targetFramework="net451" />
<package id="System.Data.SQLite.EF6" version="1.0.94.0" targetFramework="net451" />
<package id="System.Data.SQLite.Linq" version="1.0.94.1" targetFramework="net451" />
</packages>
and the app.config that worked for me had contents:
<?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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog" />
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<system.data>
<!--
NOTE: The extra "remove" element below is to prevent the design-time
support components within EF6 from selecting the legacy ADO.NET
provider for SQLite (i.e. the one without any EF6 support). It
appears to only consider the first ADO.NET provider in the list
within the resulting "app.config" or "web.config" file.
-->
<DbProviderFactories>
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
<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" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="WorkinDataEntities" connectionString="metadata=res://*/WorkinDataModel.csdl|res://*/WorkinDataModel.ssdl|res://*/WorkinDataModel.msl;provider=System.Data.SQLite.EF6;provider connection string="data source=X:\dev\proj\workin\bin\data.db"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
As you can see, somehow in the end, for me, it was not necessary to remove "EF6" from invariantName or to remove or rearrange other providers or default connection factories. I didn't have to do any reg hacks. Rearranging add/remove tags (that were added during NuGet System.Data.SQLite 1.0.94.1 package installation) in the start-up project's app.config made the difference.
After all the above, I updated EntityFramework to 6.1.2 via NuGet and both updating the model from database via designer and accessing the data at runtime still works.
I finally have steps to consistently add Sqlite and EF6 to a project:
EF6: versions 6.0.0 to be 6.1.3 (currently the latest version).
System.Data.Sqlite: 1.0.93 - 1.0.95 but not 1.0.98 (currently the latest version).
To avoid getting System.Data.Sqlite 1.0.98 , do not install using Nuget Package manager. Manually install System.Data.Sqlite. Unfortunately, http://system.data.sqlite.org/ does not readily list previous downloads.
x86 System.Data.Sqlite 1.093
x64 System.Data.Sqlite 1.093
I use Nuget Package manager and install EF6 and then I manually added System.Data.Sqlite library. I have tried multiple times to use 1.0.98 but I cannot
App.config File
For my implementation, I am working with database first an manually coding the entity data classes
public partial class MyDbContextEF : DbContext
{
public MyDbContext() : base("name=MyDbContext") { }
public DbSet<DataRecord> DataRecords { get; set; }
}
[Table("TableName")]
public class DataRecord
{
[Key]
public Int64 RowID { get; set; }
public string Name { get; set; }
}
I reported this issue and a fix is under way, and a workaround appears to be available (I have not tested it) http://system.data.sqlite.org/index.html/tktview?name=e634e330a6
I had the exact same problem--The model designer wizard was not showing my sqlite db in the dropdown list. I was able to resolve it by fiddling with the sqlite db connection and tables.
0a) I added a connection through the Server Explorer to my sqlite file (the sqlite providers and servers showed in new connection wizard for the Server Explorer but not my edmx Model Wizard)
0b) At this point it was not showing in the edmx Model Wizard still, but did show as a Data Connection in the Server Explorer.
1) I added a table to the sqlite file.
2) I closed the connection to the sqlite db through the Server Explorer
3) I opened the design of my dummy table om the sqlite file through the Server Explorer (thus reinitiating the connection)
4) I tried to "Update Model from Database..." and it was showing in the dropdown list
Another step I did not include above was I created and deleted an .mdf SQL server database New Item... > Database Service.... I did that shortly before trying the above steps. I assume that wouldn't matter but you never know.
Not sure what exactly did it. It seemed a manual disconnect and reconnect through the server explorer made VS "wake up" and display the server in the list. Try fiddling with the connection and tables a bit to see if that wakes something up.
I had this problem as well. The cause was probably that I forgot to tick the visual studio checkbox when installing the system.data.sqlite driver and then installed over that with the checkbox ticked without deinstalling the system.data.sqlite driver first. This how I solved it:
Uninstall the system.data.sqlite driver.
Reboot.
Install the system.data.sqlite driver
Delete the old solution and set it up anew, just like you did (might not be necessary).
Add the ADO.NET entity model (the template was missing for me, this answer helped with that)
The sqlite data source should now be available.

Publish Web dialog doesn't detect my entity framework 5 context as Code First

I've recently upgraded a WFC project that uses Entity Framework from v4.3.1 to 5.0.
I'm running Coded migrations only (no automatic migrations).
Previously, I was using the Publish Profiles to deploy this solution and apply the migrations. Since upgrading the project to EF5, the migrations portion no longer works and the publish dialog doesn't detect the context as having code-first migrations.
Specifically, the .pubxmlfile changed from detecting my context as <Object Type="DbCodeFirst">to <Object type="DbDacFx"> which is incorrect for my context.
As a workaround, I've manually added the <entityFramework> database initializer configuration to my web.config transforms, but I'd like to understand why the publish profiles aren't working. That was a much nicer solution.
It once happened on me when merging another developer's commit and triggered Visual Studio project reload. That's how it caused the "DbCodeFirst" to "DbDacFx" change.
If I restart Visual Studio then everything goes back to what it should be.
Just another thought.
You probably missed adding the reference to EntityFramework into your project. By just adding the reference you should be able to control whether or not the DbCodeFirst option is available or not.
As this post suggests, try using the fully-qualified name of your DbContext as the name of the connection string. Instead of:
Web.config
<connectionStrings>
<add name="MyContext" .../>
</connectionStrings>
Use:
Web.config
<connectionStrings>
<add name="MyNamespace.AnotherNamespace.MyContext" .../>
</connectionStrings>
In my case, in order to use my existing publish profiles (.pubxml), I also had to manually edit the <ObjectGroup Name="..." ...>. Probably recreating the publish profiles would work too.
I had the same issue but not in the same context.
I had been using Code First Migrations with existing ASP.NET MVC 5.2.3 application using EF 6.1.3 for a month without issues. At one point in time I added support for Windows Azure Storage but I made some mistakes:
I added a new project. Unfortunately I chose "Console Application" instead of "Class Library". I tried to fix it by changing it back to "Class Library" in "Project Settings"
I used Nuget to Install-Package WindowsAzure.Storage but I installed it on the MVC project and not on the class library. I tried to fix it by doing Uninstall-Package on the MVC project and installing it to the correct project
I called the class in the class library "WorkOrderStorage"
I added the connectionString to <connectionStrings> element in web.config and a transformation in web.release.config
I guess my project was now in an inconsistent state. I noticed that it would forget about Code First Migrations (I monitored the changes to the .pubxml file):
when I put a reference between the MVC project and the library
containing the WorkOrderStorage class
when I created an empty 'WorkOrderStorage' class in one of the existing libraries
In the end I fixed it by recreating this library correctly from scratch as a class library (because of observation 1). I also named the class WorkOrderRepository (because of observation 2).

Entity Framework Code First Data Migrations not working with VS2012 Web Deploy

I have created an MVC 3.0 application using Visual Studio 2012, .NET 4.5 and Entity Framework 5.0.
Using Code First Data Migrations, I am able to correctly propagate model changes to my local test database, but I can't figure out how to get this to work when deploying to my staging and production servers using Web Deploy.
I have read the following article ...
http://msdn.microsoft.com/en-us/library/dd394698(v=vs.110)#dbdacfx
... which explains what's supposed to happen, but it's not working for me, as Web Deploy seems unable to detect that I am using Entity Framework. The tutorial shows a checkbox to enable execution of Code First Migrations ...
... but my dialog shows the only Update Database checkbox for each database.
I have read that, in order for Visual Studio to detect the use of an Entity Framework context, the Web.config must include an element that defines it. Here's mine:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<contexts>
<context type="MyContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyContext, MyAssembly], [MyConfig, MyAssembly]], EntityFramework">
<parameters>
<parameter value="MyConnectionStringName"/>
</parameters>
</databaseInitializer>
</context>
</contexts>
</entityFramework>
Any suggestions would be greatly appreciated.
Thanks,
Tim
I have discovered the solution to this problem through experimentation.
In fact, my MVC application was created by VS2012 by converting from a VS2010 solution. Since the conversion process did not report any issues, I assumed that it had correctly converted everything, including the publishing profiles.
However, I discovered that the problem was in the conversion of these profiles and, unless I manually edit their XML files, there is apparently no way to get old imported profiles to participate in Code First Migrations.
Simply creating new publishing profiles in the converted solution results in the expected behavior.
Try this:
Enable-Migrations -Force
Ensure the below is set to true
AutomaticMigrationsEnabled = true;
Republish - worked for me