Use Entity Framework Code first with any database - entity-framework

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

Related

Code First connection string

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.

Entity Framework Code First, It always makes a new Database

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.

Using connection string in Web.config when enabling code-first migrations

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

EF5 Code First Migration problems publishing to IIS

I've created a MVC 4 project which uses EF5 Code First with migrations.
Because I was new to this topic I used the following article.
Now that the development is finished I want to publish to IIS (I use FTP or Web deployment package). So before publishing I changed the connectionstring to the right db server.
But after publishing the site I get an exception when accessing pages which make use of the DB. The exceptions refers to the fact that he can't connect to the database.
Because of these problems I decided to try it out locally on another DB server than the default one "(LocalDB)\v11.0". BTW: "(LocalDB)\v11.0" works like a charm...
While debugging I got a better look at the error.
Here is an image of the error:
What I've already tried:
Generate a sql script by executing "Update-Database -Script
-SourceMigration:$InitialDatabase" in the Package manager console. After I ran this script on the dbserver to create the db. Tables were
created but the error was still there.
I changed my connectionstring to all kinds of combination with no
results
I already used a custom user for the app pool in ISS and gave this user full rights to the DB server and the db.
Here is the most important part of my web.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=LOCALHOST\MSSQLSERVER;Initial Catalog=ProjectX;Integrated Security=TRUE;MultipleActiveResultSets=True" />
</connectionStrings>
And
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=LOCALHOST\MSSQLSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
My DBCcontext class constructor looks like
public DBContext(): base("DefaultConnection")
{
}
I guess I am missing something, this is the first time I use EF Code First with migrations.
This problem is really driving me crazy. I am out of ideas.
Just found out that the problem was caused by the connectionstring.
The string was incorrect, seems like you if you have a default SQL Server you just need to use
"Data Source=LOCALHOST".
I guess because of all the problems I had that day with the deployment i overlooked the easy parts. Yust make sure you the following things are true when you have problems like I did:
Your connectionstring has the same name as your DBContext. Another sollution could be to do like i did and add the connectionstring name to the base:
public DBContext(): base("DefaultConnection")
{
}
If you also have the defaultconnectionfactory set. Make sure to also update the Data Source there. This was one of the problems I struggled with. I didn't check the bottom of my web.config ...
If the problem still persists you can use EF profiler to have a look at the connectionstring when your app of site is accessing the DB.

How to change EF default from SQL Server Express db creation to local SQL Server 2008 Instance?

Can somebody tell me how I can setup my MVC3 applciation so that when it first creates a database that it does so in a local (or remote) instance of SQL Server 2008 instead of using SQL Server Express?
So if you're using EF, then you will use a class to connect such as
public class EFDbContext : DbContext
{
public DbSet<Product> Products
{
get;
set;
}
}
Now, you only need a connection string in your project's WebConfig file (not the webConfig in the Views folder). Add a connectionStrings section under the configuration node like this. NOTE: The class and the connection string must share an identical name - in this case, "EFDbContext".
<configuration>
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=SERVERNAME\;Initial Catalog=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"
providerName="System.Data.SqlClient"/>
</connectionStrings>
"SERVERNAME\" will connect you to the default installation. If you're looking for the default installation on your local machine, just enter your computer name and you're golden. If you prefer to use window authentication rather than SQL Server authentication, just substitute "Integrated Security=true" for the UserID/Pwd portion of the connection string. HTH
You can choose connection string using constructor as following way :
Public class EFDbContext : DbContext
{
public EFDbContext() : base("dbconninfo"){}
}
<configuration>
<connectionStrings>
<add name="dbconninfo" connectionString="Data Source=SERVERNAME\;Initial Catalog=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"
providerName="System.Data.SqlClient"/>
</connectionStrings>