Change default location of LocalDb - entity-framework

I am programming with EF5-code first and want to use LocalDb. How can I change the default location of LocalDb database file? Default location is %USERPROFILE% directory according to http://blogs.msdn.com/b/sqlexpress/archive/2011/10/28/localdb-where-is-my-database.aspx
Previously I was using SqlCe DbConnectionFactory which accepts a parameter for database path/name. If I use AttachDbFileName parameter then it raises an exception if database doesn't exist (it's supposed to create it!).

I got this working thanks to this post. The answer is simple. Basically I added
<connectionStrings>
<add name="DataModel.Context" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=database;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\database.mdf" providerName="System.Data.SqlClient" />
to the configuration section of app.config and it magically replaced the "database" with my actuall database (DbContext) name. EF code first also works perfectly to create the database if it doesn't exist.

Related

Single Connection String with Multiple Entity Framework Models(Data First)

I have 3 different project having their respective EF entity data model pointing to same database.I don't want to save connection string in each of these project's app.config file but want to share it between my models.
I see this link on stackoverflow How to share a connection string between multiple entity data model.
But the problem with it is if I will update the EF model it will overwrite the code in EF Model's context and it will inherit from DbContext not from BaseContext.
Please help how can I resolve this.
You have to move your connection string in a separate config file:
ConnectionStrings.config
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="connectionString"
connectionString="Integrated Security=SSPI; Persist Security Info=False; Initial Catalog=DbName; Data Source=.\SQLExpress;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Modify the connection string so that fit your requirement.
Then you can share it with all your projects like that:
1) Open your App.config (This file found in your project)
2) Add this line code somewhere behind </configSections>
...
<connectionStrings configSource="ConnectionStrings.config"/>
...
The trick in configSource:
"Gets or sets the name of the include file in which the associated configuration section is defined, if such a file exists."
https://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource(v=vs.110).aspx
What will happened:
ConnectionStrings.config must be first copied
All YourApplicationName.config will reference the shared connection string config file.
If the project does not have any App.config then just add it! or you can also loaded manually with ConfigurationSettings.
This is the best way to share the database configuration between the app.configs and when you change for example the Sql Server name, then you have only to modify the ConnectionStrings.config and not all App.configs!
It resolved as connection string always picked from MVC project and all other class library projects are referencing it automatically.

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.

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.

Exception with SimpleMembership and ADO.NET Entity Data Model

I create new ASP.NET MVC4 project with account controller uses forms authentification.
Then I run project and register new user for creating database file.
Then I create some tables in new mdf database file and I use ADO.NET Entity Data Model for this new tables instead of membership's tables.
After creating model.edmx there are two connection strings in web.config file.
name="Entities" connectionString="metadata=res://*/Models.Database.LAModel.csdl|res://*/Models.Database.LAModel.ssdl|res://*/Models.Database.LAModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDb)\v11.0;attachdbfilename=|DataDirectory|\aspnet-LAWebProject-db.mdf;initial catalog=aspnet-LAWebProject-db;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-LAWebProject-db;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-LAWebProject-db.mdf" providerName="System.Data.SqlClient"
The project debugs few times then crashed with following exception:
Can not connect to the database server SQL Server.
Please help me to resolve it...
Try removing that "\" from your connection strings:
|DataDirectory|\aspnet-LAWebProject-db.mdf;
becomes
|DataDirectory|aspnet-LAWebProject-db.mdf;
If it doesn't work, check that the db file aspnet-LAWebProject-db.mdf exists in the App_Data folder.
Make sure your LocalDb instance is running too:
LocalDB: Where is My Database?

Connection Strings - MVC Entity Framework - Database First

Can anyone suggest how I could programatically switch debug and live connection strings?
I've seen other people have passed an EntityConnection to the constructor from the controller like this :
private XYZDatabase db = new XYZDatabase(ConfigurationManager.
ConnectionStrings["XYZDatabase-TEST"].ConnectionString);
but it still requires manually changing it? is there a way to use
System.Net.Dns.GetHostName() or similar
to switch it automatically?
Thanks
Ayende has a post that addresses this issue.
http://ayende.com/blog/135169/frictionless-development-web-config-and-connection-strings
In my software I just have 2 connection strings of the same name in my app.config and comment/uncomment to switch between configurations.
Another method is that you could create a static property in your solution (.asax file?) and just use that to swap between XYZDatabase-TEST and XYZDatabase when you are fetching ConnectionStrings.
Add connection string to your Web.config like:
<connectionStrings>
<add name="XYZDatabase-TEST" connectionString="Server=.\SQLEXPRESS;Database=XYZDatabase-TEST";integrated security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
Then open you Web.Release.config and add
<connectionStrings>
<add name="XYZDatabase-TEST"
connectionString="Data Source=OTHERSERVER;Initial Catalog=XYZDatabase-TEST;Persist Security Info=True;User ID=sa;Password=password" providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
Now, everytime you will publish you application to deployment server using Release configuration it will use the connection string from web.release.config
Note that this transformation will not work locally when you debug. You must publish to run the web.config transformation.