Database should be placed here. SetInitializer c# ef-code-first entity-framework


I'm working on a project that may end up having several UI versions or variations, but as of right now, my solution Web has only two subprojects that have an ASP.NET MVC-based Web interface. My database context and models are defined in the context of a service project.

My objective is to have as little references to EF-specific code as possible in my web project. I want it to be independent, so I shouldn't have to make several changes to my MVC project when I replace the dlls with the service backend (from, say, SQL to XML or MySQL).

It appears as follows:

Project layout

My inquiries are as follows: - I haven't yet discovered any examples of utilizing databases. In a location other than Global.asax, use SetInitializer. In my factory-type DatabaseContextProvider class or in the service class that extracts data from context and gives it to the UI via DTOs, I'd want to include database re-creation whenever the model changes. Are there any drawbacks to such place? - Is it realistic for me to request that the context's connectionString be customizable via the Properties/Settings.settings file?

12/30/2011 12:43:44 PM

Accepted Answer

You would need a method to contact theDatabase.SetInitializer a way before the very first time theDbContext . That's why it's often referred to in theGlobal.asax file.

A class with an initialization method may be developed in yourtm.Service and call it in the projectApplication_Start approach and use theDatabase.SetInitializer this starting technique.

You may use a configuration file to specify the connection string.

12/30/2011 12:57:29 PM

Popular Answer

I would like not to place the initializer outside the Assembly that includes the DataContext in order to prevent the coupling. So I gave the DataContext a static constructor. In this manner, the initializer will be available to any projects that reference this Assembly without having to explicitly set it, and it will only need to be set once per process.

static MyDataContext()
   Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDataContext, Configuration>());

Of course, the application configuration file will be used to extract the connection string.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow