I am using Entity Framework model-first. After finishing my site, I did a Publish. I am using Entity Framework and a database connection setup using a connection string from settings.config:
<add key="thenna"
value="server=11.3.34.45;database=montage;user id=sample;password=Test;trusted_connection=false;"/>
I have config changed server database details.
My entity framework connection string in web.config:
<add name="tickandtieEntities"
connectionString="metadata=res://*/Entityframework.Tickmarks.csdl|res://*/Entityframework.Tickmarks.ssdl|res://*/Entityframework.Tickmarks.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-QD6A981\SQLEXPRESS;initial catalog=tickandtie;user id=sa;password=tickmarks;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
When I change web.config file with server details I get an error
Cannot open database "tickandtie" requested by the login
How can I configure Entity Framework in web.config when I move my app to the host server? Please help me anyone
You can do this by setting the connection string on your EF Db Context at creation time, passing your setting value to your EF context.
E.g.: adding a constructor on your context, which uses the base DbContext constructor to pass the connection string:
public class MyDbContext : DbContext
{
public MyDbContext(string connString) : base(connString)
{
}
}
Which then make your context used like:
var connectionString = "" // Get the value of of your custom config file here.
var ctx = new MyDbContext(connectionString);
As stated above, you need to read your connection string value first out of your settings.config file.
Related
Just for a brief overview this is how I added the database into my project:
I have added a datasource by adding an ADO.NET Data Model Entity and selecting EF Designer from Database.
Doing so has generated a connection string for me in my web.config. Integrated Security is set to true (if that matters).
Once connected I right clicked and selected 'Update model from database.
Since there is multiple environments I built a custom context with a parametized constructor. Code looks as such (condensed and censored):
public partial class DataEntities : DbContext
{
public DataEntities(string connectionString)
: base(connectionString)
{
}
}
With each environment there are different local sql accounts associated. Requiring me to generate a connection string that is associated with the correct account in the correct environment. Doing so my web config looks something like this:
<connectionStrings>
<add name="DataEntities" connectionString="metadata=res://*/Models.XXModel.XXModel.csdl|res://*/Models.XXModel.XXModel.ssdl|res://*/Models.XXModel.XXModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MYSQLSERVER;initial catalog=Data;integrated security=True;MultipleActiveResultSets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<secureConnectionStringsSection passwordPolicy="AllowLocalPasswordsForConnectionStrings">
<secureConnectionStrings>
<add name="DataEntities-Local" providerName="System.Data.SqlClient" connectionString="data source=MYSQLSERVER;user id=ACCNT; password=PASSWORD;" />
</secureConnectionStrings>
</secureConnectionStringsSection>
When I am instantiating my DataEntity object, I am calling a helper function I have written to get my custom connection string. I am doing so via the following code:
private DataEntities adDB = new DataEntities(XXX.Helpers.EFDBHelper.getDataConnectionString());
I can verify that my connection string helper does correctly pull the custom connection string that I have in my web.config. However once I actually try to make a call on the database I am left with the following error:
Invalid object name 'dbo.mycolumn'.
I know that my parametized constructor is being called with the correct connection string. I also know my connection string is valid, I have tested it in powershell:
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "data source=MYSQLSERVER;user id=ACCNT;password=PASSWORD"
$conn.Open()
$conn.Close()
I am certain that it is not an issue with the database itself as well. The moment I remove the parameter from my Entity initialization:
private DataEntities adDB = new DataEntities();
I am able to pull data from the database. I am assuming that it uses the auto-generated connection string. Which won't work since I cannot use integrated security once it goes past my local environment.
My apologies, I am new to the technology here. I am sure that it is just something small that I am missing.
In my connection string I did not specify a catalog.
Since I am newish to the technology, I tried to simply replicate some of the existing code that I had inherited. In the connection string I tried to replicate from, no catalog was expressed as well.
However... the account I am using to talk to the new datasource has access to all levels of the database so the catalog was required. The old inherited database had only one catalog the the sql account had access too.
You live and you learn!
In my MVC projects with a web interface, I'm used to setting the Connection String in the Web.Config file.
However, now I'm making a bog standard console application - also with a database hook, but how do I set the connection string globally for the application?
At the moment, I am setting
var dbIndex = new DBContext();
dbIndex.Database.Connection.ConnectionString =
"Data Source=USER-PC;Initial Catalog=TextProject.DBContext;" +
"Integrated Security=True;MultipleActiveResultSets=True";
but I have to set this connectionstring property every time, in all function calls. Is there a way to set a global connection string when I don't have a web.config?
So I think what your saying is that Entity Framework (I assume that is what you are using) looks for defaultConnection connection string.
You can try putting it in the app.config file as suggested by others, but I'm not sure if this will be automagically picked up by EF.
What you could do, if it doesn't work, is to create new class which inherits DbContext -
public class MyDbContext : DbContext
{
public MyDbContext() : base()
{
var cs = ConfigurationManager.ConnectionStrings["defaultConnection"]
.ConnectionString;
this.Database.Connection.ConnectionString = cs;
}
}
App.config is the equivalent to a Web.config for console or .exe programs.
Add a reference to System.Configuration on any project that you want to use the ConnectionStrings of the app.config
Add a AppConfig to your entry point project. This is the project that is executed. (e.g. console .exe)
Add the connection string in the <connectionStrings></connectionStrings> section of the app.config
Now place the connection string in your app.config
string connStr =ConfigurationManager.ConnectionStrings["ConnName"]
.ConnectionString;
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnName" connectionString="Data Source=USER-PC;Initial Catalog=TextProject.DBContext;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>
As others have said put your connection string in the App.config file.
Regarding Entity Framework. If you are using Entity Framework (EF) version 6.2.0 perhaps earlier EF will automatically look for a connection with the same name as the class that inherits from DbContext.
If your class is
public class MyDatabaseContext : DbContext
{
// other code
}
EF will look for a connection string with a name like this
<add name="MyDatabaseContext" ...
You can also set the name in the constructor like so
public class MyDatabaseContext : DbContext
{
public MyDatabaseContext() : base ("name=defaultConnection")
{
// other code
}
// other code
}
In this case your connection string name can be <add name="defaultConnection" ...
You can put the same element in a App.config file for the console application and access it the same way you would a Web.config.
Related: What is App.config in C#.NET? How to use it?
The solution is very simple and easy. Just right click and set the project as start-up project. entity framework by default picks the start-up project and uses the connection string inside of App.config or web.config
Please refer to this:
So I have Solution with two projects. The first projects should act as a Data Access Layer so there in the app.config file I have this:
<connectionStrings>
<add name="BloggingContextCF"
connectionString="provider=System.Data.SqlClient;
provider connection string="
data source=*****\SQLEXPRESS;
initial catalog=CodeFirst.Blogging;
integrated security=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
The second Project is a ASP.NET Web Forms project, where I removed the default connection string pointing to the (local) instance leaveing only one connection string, the one from the first Data Access Layer project. Which actually works and the database is created on my SQL 2008 R2 server, but instead of the desired (and expected) database name - CodeFirst.Blogging the name is DataAccessLayer.BloggingContextCF where DataAccessLayer is the name of the project and BloggingContextCF is the class extending DbContext.
What I need to change in my connection string so I can get the desired name?
Try
public BloggingContextCF ():base("CodeFirst.Blogging") {}
make the connections string like
Point it to sql client
providerName="System.Data.EntityClient"
to
providerName="System.Data.SqlClient"
For full connection string do it like
<add name="BloggingContextCF" connectionString="Server=YOUR_SERVER;Database=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
For more connectionstring example follow the link
and don't forget to modify your dbcontext
public class YourContext : DbContext
{
public UsersContext()
: base("BloggingContextCF"){ }
}
Transform web.config won't work well for Entity Framework CodeFirst because the connection string is added dynamically after transform when publishing. We have a dynamic connection settings being set in code for CodeFirst when releasing to different environments.
I have tried the correct removal method but the published results ends up with the connection string in the web.config.
Are there any work arounds for this? Putting connection info in our web.configs isn't an option. Adding the connection info dynamically at runtime works well.
The problem is when publish adds the connection info in the web.config the app gets a 500 error because codefirst is attempting to use an invalid connection string for the environment that is not sandbox where it was created.
We are changing that at runtime here and that is working.
public MyAppDataContext()
{
this.Database.Connection.ConnectionString = OurDynamicConfigSettings.GetSetting("MyAppConnectionString");
}
The codefirst though is attempting to use what is in web.config before we set it dynamically. The fix is to remove the connection info from the web.config.
It all works except when building on build server or publishing, codefirst inserts the connection info back into the web.config every time we publish. Having to remember to remove this each time is not good practice and prone to errors if you forget.
Code for removing connection string in our transform file should work but doesn’t.
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[#name='MyAppConnectionString'])" />
</connectionStrings>
Your transform should be:
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="Match(name)" name="MyAppConnectionString" />
</connectionStrings>
But, I have to ask.. are connection strings stored in your database or something? Why do you need to do them in code?
You could just do this:
public class MyDataContext : DbContext {
public MyDataContext(string connectionString) : base(connectionString)
...
}
Then when you create you contexts, you do this:
using(var context =
new MyDataContext(OurDynamicConfigSettings.GetSetting("MyAppConnectionString"))) {
...
}
public partial class MyContextEntities : DbContext
{
public MyContextEntities(string ConnectionString="[Your Entity Connection String Here]")
: base(ConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Replace " with ' (single quote) in connection string
I have a local ASP.NET MVC 3 Windows Azure Project where I use a local instance of MSSQL Express for my emulator.
In my web.config I have the following connection string:
<add name="ExampleDb" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ExampleDb;User Instance=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
For debugging purposes I have the following in my WebRole.cs file:
public override bool OnStart()
{
ExampleDb context = new ExampleDb();
context.ExampleItemEntries.Add(new ExampleItem() { ExampleItemId = 1, Att1 = "1", Att2 = "2" });
context.SaveChanges();
return base.OnStart();
}
When I perform this action I can actually see the content in my code-first generated database (using Entity Framework). Database: ExampleDb, Table: ExampleItem.
However, doing the exact same thing in ExampleController does NOT update the database. Instead this data goes somewhere else (I have no idea where). When I visit my controller via the browser I can upload data and look at it but it is not stored in my ExampleDb database, only data sent from WebRole.cs is in the database.
Any ideas what's causing this behaviour?
ExampleDb.cs looks like this:
public class ExampleDb : DbContext
{
public ExampleDb() : base("ExampleDb") { }
public DbSet<ExampleItem> ExampleItemEntries { get; set; }
}
Your connection string contains 'User Instance=True'. This means that SQLEXPRESS uses a user instance to store your data. This is a completely different instance of SQL Server that contains a new set of databases.
I assume the code in WebRole.cs is run in a different user account than the code in ExampleController. When the ExampleController is run under a user account that is not an administrator, a user instance is used...
So when you remove 'User Instance=True' from your connectionstring and assign the proper access rights to your SQLEXPRESS database instance, that would solve the problem.
In CodeFirst Model you should define the connection string in the web.config first as below:
<connectionStrings>
<add name="ExampleDbConnection"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
database=ExampleDb;
AttachDBFilename=|YouDataDirectory|yourdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
<connectionStrings/>
The DbContext class constructor accepts a name-value pair specifiying connection-string name in web.config. So you can reference this connection string in your context:
class ExampleDb : DbContext
{
public ExampleDb() : base("name=ExampleDbConnection") { }
...
}
This code does work fine in a ASP.NET MVC Web Role so you can try as above.