EF Migrations Database connection string is wrong - c#

When I use update-database -verbose and check the connection string it is wrong, no wonder the command returns with a crazy list of errors. In app.config my conn string is:
dd name="TESTDBConnString" connectionString="data source= .; initial catalog=TESTDB;
integrated security=True" providerName="System.Data.SqlClient"
And in my context class my constructor is:
public class MyContext : DbContext, IContext
{
public MyContext() : base("TESTDBConnString")
{
}
public DbSet<TestModel> TestModel { get; set; }
}
Yet when I run the verbose command I see .\SQLEXPRESS being used as the database source and I cannot even use that in SSMS so can someone show me how to get it to simply take '.'. Thanks!

it looks like your connection string format is invalid.
from the MSDN:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="BloggingDatabase"
connectionString="Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" />
</connectionStrings>
</configuration>
it seems like you need to specify Server and Database for current Entity Framework apps connecting to SQL SERVER

I can't comment that's why i will make a suggestion. In .Net core app you need to have a specific structure in appsettings.json
Like
{
"ConnectionStrings": {
"TESTDBConnString": "server=localhost\\SQLEXPRESS;Initial Catalog=my-DB;Integrated Security=true;Trusted_Connection=True;connect timeout=100;"
}
}
For login-password connection string a little bit different.
In this case in the context for empty constructor you can use like. And all should work when you call Update-Database.

Related

How do I set a default connection string in a console application?

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:

How to set the database name in the connection string with Entity Framework 5

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"){ }
}

Remove ConnectionString from Web.config using Entity Framework CodeFirst

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

DataContext does not contain a constructor with 0 parameters

I am learning with this so bear with me...I am trying to create the DB object to access the table.
AppDatabaseDataContext appDb = new AppDatabaseDataContext();
This gives me an error, so I create the constructor...
public AppDatabaseDataContext()
{
}
Now this tells me that System.Data.Linq.DataContext does not contain a constructor that takes 0 parameters. Why?
Thanks!
You need to specify a connection string. If you know it's always going to be the same (for example, localhost) you can just hard-code it in your parameterless constructor:
public AppDatabaseDataContext()
: this(#"Data Source=localhost;Initial Catalog=Foo;Integrated Security=True")
{
}
Notice how we chain the constructor to call the version that consumes a connection string. This way, you can instantiate the data context using the parameterless constructor, and it will use this default connection string.
Sometimes LINQ2SQL might become messy on properties window and the connection string might disapear.
If you can, restart all over, remove de Dbml and but DON´T FORGET to delete from the web.config the connection string. Add a new Linq2SQL to your project and let the LINQ2SQL to create the connection string for U in the web.config.
It's strange. Every time I've used a "LINQ to SQL" DataContext in the past, it's always created a 0-argument constructor for me.
But today, I was finding that sometimes, in the Designer, it wouldn't let me select a particular (known) connection string in the Properties window... and when this happened, it refused to create this 0-argument constructor.
The solution was to manually add it myself.
My web.config contained a connection string called MikesConnectionString :
<configuration>
<connectionStrings>
<add name="MikesConnectionString" connectionString="Data Source=localhost;Initial Catalog=MikesDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
... so in my survey.designer.cs file, I added this:
public SurveyDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["MikesConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
Job done.
But odd. Very odd.
Just Change your connection string just like
<connectionStrings>
<add name="DBLabConnectionString"
connectionString="Data Source=.\SQLExpress;Initial Catalog=DatabaseName;
Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

DbContext behave differently within different classes

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.

Categories