Right now, in development I have the following code in the Global.asax.cs file that calls the Entity Framework (v4.1) SetInitializer with my SeedSampleData method. This all works perfectly.
However, I would like to store the SetInitializer "strategy" parameter through a web.config setting so that I can create a deployement script that will automatically set it to new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>() instead of my seed method during production deployment.
The reason for wanting to move this to the web.config is that when I roll out a new deployment to the production server I want to make sure that I don't accidentally leave my seed initializer in the code.
protected void Application_Start()
{
//TODO: Figure out how to move the following lines to web.config and have a deployment script modify it when going to production.
//This line is for production
//System.Data.Entity.Database.SetInitializer(new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>());
//This line is for development
System.Data.Entity.Database.SetInitializer(new Domain.Concrete.SeedSampleData());
//... Remainder of Application_Start calls here...
}
If you update to EF 4.3 (which is a good idea anyway), then you can use something like this in your web config:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<entityFramework>
<contexts>
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
</context>
</contexts>
</entityFramework>
</configuration>
Rowan wrote about it in detail here: http://blogs.msdn.com/b/adonet/archive/2012/01/12/ef-4-3-configuration-file-settings.aspx
If you really want to keep using 4.1, then there is an older syntax that you can use instead. I wrote about it here: http://blog.oneunicorn.com/2011/03/31/configuring-database-initializers-in-a-config-file/
If I understand correctly, your SeedSampleData initializer is used only for debug purposes?
I don't know if there is a config parameter to control this, but you can use preprocessor directives:
#if DEBUG
System.Data.Entity.Database.SetInitializer(new Domain.Concrete.SeedSampleData());
#else
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>();
#endif
(assuming, of course, that you don't deploy debug assemblies in production...)
Related
I am working on a older webservice, which uses Entity frameworks 6 to connect to Database.
The project is split up into web-service (controller) and "repository", which operated the database.
The idea is to now create an EXE which calls the repository, hence class library, which uses Entity framework. However, here I have some settings issues with connecting to the database.
The repository's config holds connection data, but for some reason it cannot connect.
Running is a default, hence default setting (none) of my exe, I get this error:
I can debug in into
public partial class My_TestEntities : DbContext
{
public My_TestEntities()
: base("name=My_TestEntities")
{
}
It crashes at that moment.
"Exception has been thrown by the target of an invocation." - which points to something deeper that just this.
I try to copy default into my own app.config
<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="my_TestEntities" connectionString="metadata=res://..... stuff here..." />
</connectionStrings>
<appSettings />
This results in
"The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception."
Copying the full config from the repository, some web stuff etc results in the same
Copying the configuration from the controller results in same as well.
I tried those things as I don't know what to do. I googled and found nothing.
So maybe here I can get some good ideas
I can answer this myself.
The parent exe calling the repository needs to have Entity framework (nuget package) installed, this will add some parts automatically to the config, as above.
Next, only the connection string is needed in the config file.
Then it works
I'm playing around with EF different workflows. Yesterday I made a new project and Entity Framework 6 was the first suggestion from Nuget so I decided to give it a try, also it is a very small project entirely for learning purposes so I guess it will be good experience to try EF 6 since I've been working mostly with Ef 5.
My Application is based on Code First approach. The structure of the solution is shown in the print screen:
The project CodeFirstClasses is meant to hold my Entites. For simplicity purposes and because I follow a tutorial I use only one class as you may see - Customer.cs. There I have :
public class RewardContext : DbContext
{
//Specify the name of the base as Rewards
public RewardContext() : base("Rewards")
{
}
//Create a database set for each data item
public DbSet<Purchase> Purchases { get; set; }
public DbSet<Customer> Customers { get; set; }
}
And the other classes - Purchase and Customer which are trivial, so I won't paste them here.
The other project as you can see is Windows Forms project with just one form and button on it. On the click event of the button I have all the logic for adding new records to my two entities hardcoded. Here is just a part of it:
//some code...
//Add the record and save it
context.Customers.Add(newCustomer);
context.Purchases.Add(newPurchase);
context.SaveChanges();
MessageBox.Show("Record Added!");
So far nothing different from what I'm used to with EF 5. I can build the project, I can run it, and everything is executed as expected. However I get this warning from the title :
Warning 1 The element 'entityFramework' has invalid child element 'providers'. List of possible elements expected: 'contexts'. And even though I'm using mostly MS SQL Server Management Studio I've noticed that I'm not able to manage my connections/databases from the IDE - Visual Studio 2012, but this was not an issue with EF 5.
My research narrowed down the possible source of problem/solution to manually changing the App.config file, but this is an area where I haven't got much experience especially when the IDE took care of it until EF 6. So I'll post both my App.config files for this solution :
The one from the CodeFirstClasses 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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
And from my TestCodeFirst 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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
And the other possible solution that I found is : updating the xsd for "validating" EF config section in web/app.config file to recognize newly added EF6 elements which I'm also not aware of how exactly to do it.
Even though when I open the MS SQL Server Management Studio I see the database created for this application, the records are saved and generally it seems to work but yet I would like to resolve this warning and get to know how to set up my applications based on EF 6 right.
You can install the EF6 Designer for VS2012 from here and it will update the schema that validates config files.
The configuration schema was changed from version 5 to 6. As it says, the providers node was replaced with a contexts node.
The idea is that you can configure the providers individually instead of all contexts using the same provider. (This goes in tandem with being able to have multiple contexts that reside within one database. This used to be called multi-tenant but was later renamed to be more concise)
i have a solution that contains an MVC project and windows class library project that uses entity framework and is a data access layer. I tried to enable migrations with the following package manager console line
Enable-Migrations -ProjectName PortlandRoad.DAL -ContextTypeName PortlandRoadDBContext -Force
I try to update the database using the following line
Update-Database -Verbose -Force
if i do this with the mvc project as the startup project it works, but uses the connection string in the mvc project web.config. If i do this with the dAL project as the startup project i get the following error :
A file activation error occurred. The physical file name '\PortlandRoadDB.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
the app.config file for my DAL project is as follows :
<?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" />
<!--<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />-->
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=PortlandRoadDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\PortlandRoadDB.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
can anybody tell me how to correct this so that the migrations work specifically for the dal project and are not dependent on the MCV project being the startup project
thanks
I've the same issue in a WPF project.
I think that you have two options.
Option 1
At startup in you windows project try to specify the correct path to your database using
AppDomain.CurrentDomain.SetData("DataDirectory","your\physical\path");
With this, you will have the same error but your migrations can still being applied to your principal database.
option 2
Find a way to replace dynamically this |DataDirectory| in your app.config file before starting your application. (.bat , or .ps or ...).
another option: The bad one.
Before running your migration change the path to you DataDirectory to a physical temporary one in your app.config (this file will help you keep up to date migrations history)
before launching your application replace the temporary file path by |DataDirectory| and change this parameter in your startup with the App.config
With this work around, if your are planning to deploy your application, you will keep track of all migrations in order to anticipate futures database modifications.
VoilĂ .
Could it be that you're using "|DataDirectory|" in the connection string in the DAL project? Since "|DataDirectory|" is an Asp.Net folder and the DAL project is not an Asp project it probably doesn't recognize that as a directory and it probably doesn't exist thing the DAL project.
I was trying to generate "views" to enhance the performance of my application. The application is Silverlight 4 linked with RIA services to the Server. The server application started with EF 4.1 + RIA Services.
I installed "EF Power Tools Beta 3 v0.7.0.0" and could generate my views with no problem. But I soon realized that EF 4.1. was not able to benefit from the precompiled views. EF >= 4.2 was required.
Through NuGet I saw an update for RIA Services (RIAServices.EntityFramework.4.2.0) which used EF 5. I installed and got everything working but when I try to generate views I get an exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
I've tried reinstalling PowerTools. No luck
I've downloaded source code for PowerTools and debugged the Exception. Apparently PowerTools was trying and could not find the old EF version. The LoaderExceptions property read:
{System.IO.FileNotFoundException: Could not load file or assembly 'EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies.
I've investigated the PublicKeyToken and confirmed that it is the same as the EF 5 (EF 4.4 target=.NET 4) dll found in my "bin" output map. But PowerTools is looking for EF 4.1.. why?
My web.config file has this:
<sectionGroup name="system.serviceModel">
<section name="domainServices" type="System.ServiceModel.DomainServices.Hosting.DomainServicesSection, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication" requirePermission="false" />
</sectionGroup>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
and:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.4.0.0" newVersion="4.4.0.0" />
</dependentAssembly>
</assemblyBinding>
I've also tested changing the PublicKeyToken in Web.config just to confirm that I get another error from PowerTools thus PowerTools seems to parse my Web.config.
Update:
I've created a new Web project and added all Model code files as links. Same connectionstrings. Now i can build views.. strange.. same references.
When I add the views to my original project the RIA services won't start. Removed views and they started again.
I'm trying to use Entity Framework 5 Code First.
I've created model classes and context.
After that following Microsoft instructions I've enabled code migrations.
Than I skipped running my application (during which DB should be created first time) and use Add-Migration command. Migration was generated successfully.
Update-Database call was also successfull. But I'm not seeing my DB at all. It is absent!
SQL Management Studio and Visual Studio Server Explorer show only 4 default system databases and that's all!
I also tried to launch my application - it doesn't change anything.
I'm using
public MyContext() : base("name=MyContext") { }
such type of constructor (so I need specify connection string with MyContext name.
Here is my app.config example:
<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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="BettyContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=MyDB.sdf"/>
</connectionStrings>
</configuration>
I have no idea what's going on. Seems that no one has such problem. May be I've missed some evident thing, but howbeit I'm waiting for some help.
Do you see an exception? If you don't see an exception you probably are not looking at the right database. You can try adding some data to the database with your app and then read it. If the data can be successfully added and read and you still don't see the database it would confirm that you are looking at wrong database.