I have multiple connection strings in Web.config (for databases that should all have the same exact schema), and my DbContext is initialized with a connection string dynamically:
public MyDbContext(string connectionStringName) : base(connectionStringName)
{
}
I do not have a default constructor for MyDbContext as it is meaningless in my case. I decide which connection string to use based on the Id value of each entity (custom sharding).
I'm trying to run enable-migrations for my DbContext, but I'm getting the following error:
The target context 'MyDbContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
I've seen a sample implementation of IDbContextFactory like so:
public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
public MyDbContext Create()
{
return new MyDbContext("connectionStringName");
}
}
How is this going to help me? Isn't the connection string still hard-coded? How could I add migrations for each database?
And how about providing default constuctor for that DbContext and then when you call scripts add-migration and update-database you may use -ConnectionStringName and -ConnectionProviderName attributes to point to database you want to use.
By the way - enable-migrations script does not do much - it addes Migrations folder to your project and Configuration class. You might do it yourself.
Best Soution is to use a separate file where you will mention list of Id values against a connection e.g in
<connectionStrings>
<add name="MyConn1"
connectionString="#your connection string"
/>
<add name="MyConn2"
connectionString="#your connection string"
/>
and then in
<appSettings>
<add key="MyConn1" value="entity1,entity2" />
<add key="MyConn2" value="entity3,entity4" />
</appSettings>
Then dynamically load your connection string in some global variable
public MyDbContext() : base(MyConnectionManager.connectionStringName)
{
}
You can do it using IoC as well. Look at the sample code.
https://github.com/aamir-poswal/CodeSample
Especially
- Bootstrapper.cs
- CRMContext.cs
- DatabaseFactory.cs which you need to customize in your context
Related
I have my API hosted on Azure and in api's WebConfig I have connection string to azure database
<add name="FilmNetConnectionString" connectionString="Data Source=filmnet.database.windows.net;Initial Catalog=filmnetDb;User ID=sa;Password=password;" providerName="System.Data.SqlClient" />
I have defined my database initializer and I want to initialize my azure database. I have tried to initialize that way however it is not working my azure database is still empty
public class FilmNetContext : DbContext
{
public FilmNetContext() :
base("FilmNetConnectionString")
{
Database.SetInitializer<FilmNetContext>(new FilmNetDbInitializer());
Database.Initialize(true);
}
how can I seed my database?
Add the initialiser to the Application_Start method in your global.asax file. That should do the trick.
I have an error:
An exception of type 'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException' occurred in DataAccess.dll but was not handled in user code
Additional information: 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.
In DataAccess project I have an EF 6 with App.Config file with string:
<connectionStrings> <add name="CVJobOnlineEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model 1.msl;provider=System.Data.SqlClient;provider connection string="data source=STEFAN-PC\SQLEXPRESS;initial catalog=CVJobOnline;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
and in my second project, which is the main Start-Up project I have in WebConfig:
<connectionStrings>
<add name="CVJobOnlineEntities"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=CVJobOnline;Integrated Security=True;"/>
So, obviously I am mixing EDMX and CodeFirst conn strings, but, I need it CodeFirst because of my Identity tables which I was incorporate in my SQL SERVER DB.
Also in my DbContext, I recalled base to use FirstCode (Model1.Context.cs):
public partial class CVJobOnlineEntities : DbContext
{
public CVJobOnlineEntities()
: base("name=CVJobOnlineEntities")
{
}
You must specify your connection string only once at the entry point of your application. Your DataAccess project does not need a connection string if it is not executable. Cut & paste the connection string from your DataAccess project to the web configuration file of your application entry point, overwriting the old one.
The problem was not exactly mixing two types of connection strings, since the one from DataAccess was never read by the Entity Framework. The one provided at your entry point config was just wrong in your scenario, because you are using model-first and not code-first.
I'm new here and in Entity Framework too! i have a problem!
This is my Connection string in web.config:
<add name="SolutionName.DALClassLibrary.Setting.ShConnectionString"
connectionString="Data Source=(localdb)\v11.0;AttachDbFilename=|DataDirectory|ASH.mdf; Database=ASH.mdf; Initial Catalog=ASH;Integrated Security=True;User Instance = true ; MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
And i wrote this ConnectionString in App.config in DAL project and setting of project too.
This is my context constructor:
public ASHContext(): base("ShConnectionString")
{
Database.SetInitializer<ASHContext>(new MigrateDatabaseToLatestVersion<ASHContext, Migrations.Configuration>());
}
When i run the project in App_Data it makes a new Database with ShConnectionString.mdf name. But i have ASH.mdf database in App_Data already.
It can't find connectionstring or ConnectionString is wrong? or the problem in somewhere else?
Sorry for my poor English language.
You're passing the wrong name to DBContext. Either use ShConnectionString as name in your configuration settings or change the name for DBContext to the one used in configuration.
I use SQL Server developer edition and would like to use EF code first. I found many articles explaining how to work with either a localdb or SQLExpress. How do I tell my project to rather use my ..\SQL2008 instance?
I'm thinking that somewhere, somehow, one must be able to tell the project to use a specific connectionstring. But where? Adding it to my app.config file doesn't work. This is what I've tried:
<connectionStrings>
<add name="Context" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TimeApp;Data Source=Amanda-PC\SQL2008; MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can specify which connection string to use by passing the name of the connection string to the DbContext.
public class YourContext : DbContext
{
public YourContext()
: base("Context")
{
}
}
See this for more information
I have EF 5.0 code-first VS 2012 project and all Entity Framework menu commands (View Entity Data Model DDL SQL) produce "Exception has been thrown by the target of an invocation" popup. I think what has also changed is that EF Power Tools Beta 1 (or VS 2010, I am not sure) use to display EF Power Tools messages in the output window. Now all I get is the popup... Is this VS or Power Tools issue?
this is my work around:
Comment the constructor out, and leave the static MyDbContext as is -->
public class MyDbContext: DbContext
{
public static string ConnectionName = "Name = SMS_ADvTECHContext";
static MyDbContext()
{
Database.SetInitializer<SMS_ADvTECHContext>(null);
}
/* public SMS_MyDbContext()
: base(ConnectionName)
{
}*/
}
Then if you right click the context class --> Enityframework --> View Entity Data Model (read-only) it generate the view!
I ran into this error when I didn't have the correct default connection factory configured in the App.config inside the project that included my DbContext class. I updated it to use the correct factory and this error went away. In my case I set it to use the LocalDbConnectionFactory:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
In ran into this error and it was an even simpler issue ... the project that contained my Context was not the Startup Project. Once I set the project to be the Startup Project it started working.
Maybe Visual Studio is having trouble figuring out what connection string to use for your DBContext, when you choose the Entity Framework menu commands.
In my case, I was able to resolve this by verifying that I had a "default" connection string for my dbContext. So that, when you right click on db context and choose Entity framework, you will have a connection to the DB.
In other words, I had modified my DBContext to select the connection string from a command line parameter to my app. So, normally, my db context did not have a "default" value.
public class MyDbContext : DbContext
{
public static string ConnectionName;
public DnnDbContext()
: base( "Name=" + ConnectionName) {
}
As you can see, I had no ConnectionString by default.
I changed to:
public static string ConnectionName = "DefaultConnNameInAppConfig";
I ran into this when I had multiple connection strings with the same name configured in my web.config.