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

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.

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.

Change default location of LocalDb

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.

Entity Framework DbContext Connection string in app.config/web.config not being seen

So, I have followed this instruction from ADO.NET team blog to try to make a small test project.
I have double-checked everything. It doesn't seem to work and keeps saying connection string is missing.
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Step. 1
Build this UserModels.dll. In the dll, App.Config file, edmx generated this connection string: (hit the 'test' button when making it, and it connects successfully, and generated the edmx diagram of all the tables from 'UserDatabase')
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="UserModelsContainer" connectionString="metadata=res://*/UserModels.csdl|res://*/UserModels.ssdl|res://*/UserModels.msl;provider=System.Data.SqlClient;provider connection string="data source=MyDesktop\SQL2008;initial catalog=UserDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Step 2.
Then I made a test project:
class UnitTetst1 ....
TestMethod1()....
using (var db = new UserModelsContainer()) {
int i = db.Users.Count(); // <---expecting '0' for a new db, but I get an exception
}
---------PROBLEM HERE -----------------
Step 3. Run the test. Then I get an error InvalidOperationException like this:
"No connection string named 'UserModelsContainer' could be found in the application config file."
Seems like DbContext doesn't know where to pick up the connectionStrings from App.Config??
Please help~~
When running a program, it's the app.config of the .exe file being run that is read. The app.config of the .dll is never used. Since UserModel.dll is a dll, there must be an .exe (or web site) somewhere that you run. Place the connection string in that exe's app.config (or if it is a web site in the web.config).
I had this issue when I was attempting to do an update-database command from the "package manger console". I had a separate project for my code first Data access layer and another for my web project, etc
I was using the following command: "update-database -projectname MYPROJECTDANAME -CONNECTIONSTRINGNAME CONNECTIONSTRING -Force"
so it pointed at my MYPROJECTDANAME project however it takes the connectionstring name from startup project you have specified. Therefore make sure the project you have marked as the startup project has the required connection string.

referencing edmx in mvc project

I have a EF connection string in an MVC project like so:
connectionString="metadata=res:///Models.db.csdl|res:///Models.db.ssdl|res://*/Models.db.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=SystemName;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"
All is well until I added a second project and referenced the MVC project that contains the edmx, but during runtime I get:
The specified metadata path is not valid. A valid path must be either an existing directory, an existing file with extension '.csdl', '.ssdl', or '.msl', or a URI that identifies an embedded resource.
I've read post after post, but I can't figure out how to correctly reference the metadata in the MVC project. Can someone point me in the correct direction? I don't want to create a connection string that is so specific it breaks during deployment and debug.
The format for resources is:
Metadata=res://<assemblyFullName>/<resourceName>.
The lazy way is to use a wild card res://*/bah.msl. Which would load the model/mapping files from the bin directory, calling assembly, as well as referenced assemblies.
In your case:
res:///Models.db.csdl|res:///Models.db.ssdl|res://*/Models.db.msl
Is incorrect, try:
res://*/Models.db.csdl|res://*/Models.db.ssdl|res://*/Models.db.msl
Complete string:
connectionString="metadata=res://*/Models.db.csdl|res://*/Models.db.ssdl|res://*/Models.db.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=SystemName;Integrated Security=True;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient"
Alternatively you could use absolute references which is faster(but I am assuming this will be much more painful for you):
Metadata=res://<DLL>, <Version>, neutral, <SN>/Models.db.csdl|Models.db.ssdl|Models.db.msl