Changing connection string without recompile - c#

I'm working on a WinForm application. I've implemented data-access logic into a "library project" that I set as reference in my WinForm project. I'm using LINQ to SQL to connect to my project database, mapping the tables I use into a dbml file. Now I have to publish my project and change the connection string to point to the production DB.
Is it possible to change the connection string without re-compile the project?
It'll be very useful at debug-time and for maintenance...
I've tried to change it in app.config and also in the Settings file, but it seems to still point to the development DB.
Where am I doing wrong?

The solution suggested in this article is very good: http://goneale.com/2009/03/26/untie-linq-to-sql-connection-string-from-application-settings/
But I decided to solve my issue in a different way.
Without modifying anyting in the dbml file I added in my DAO class a constructor that takes a parameter:
public MyDataAccessClass(string connectionString)
{
_connString = connectionString;
}
then instead of using DataClasses() constructor to instantiate the LINQ-TO-SQL class, I replaced it with DataClasses(_connString).
Now I can use the data access library where I need. The connection string will be set in app.config of the referencig application (or anywhere else).

Related

VS is storing my data in some other database?

Visual studio creates a new database out of thin air to store my data. This is my DbContext:
public class LinkedDataContext : DbContext
{
public DbSet<LinkedData> LinkedData { get; set; }
}
No errors are being thrown, I just end up with another database that is only visible through the SQL Server Object Explorer unlike my initially created database which is the top one in the screenshot.
Edit
I migrated the whole accounts database generated by the MVC project to the MSSQL 2014 server. I simply added a database there and changed the connection string, then it automaticaly populated the database with the needed tables.
So I created my custom table, exactly as it was in the local database. I removed the local databases, the other connection strings and the Controller. Then I rebuild my project and created the controller again. But VS/MVC/EF or whomever is responsible is still creating a local database for my custom data.
When I create the controller it seems to find my table in MSSQL SERVER 2014, otherwise I would get a safe dialogue to store the sql file locally. So what is really happening here? Like I said, the account functionality worked instantly like a charm. My custom table in MSSQL simply won't get used.
EDIT
So I set the DefaultConnectionFactory in Web.config to my MSSQL SERVER 2014 and now it is generating a new Database inside my MSSQL SERVER. It seems to be the namespace, when I create a controller I need to pass in the namespace for the both the Model class and Context class.
Model class: LinkedData (DataVisualization.Models)
Data context class: LinkedDataContext (DataVisualization.Models)
The databases that keep getting generated automatically to hold my custom data are called: DataVisualization.Model.LinkedDataContext.
Does anyone have any idea what is really going on here?
I believe it is just the connection string in your Web.config. When you create a DbContext from an existing database outside of your project, Visual Studio prompts
The connection you selected uses a local data file that is not in the
current project. Would you like to copy the file to your project and
modify the connection?
If you select Yes, this copies the database file into your project, sets its Build Action to Content, sets a relative reference to it in your connection string and sets it to copy to your output directory on build.
If you modify the connectionString in your Web.config to point to the correct database you should be set (for future reference, answer No when asked if you want to copy it, unless that is really what you want to do - e.g. for a database file you're distributing with your binaries).
As an example, see the two connections listed below. You would see something like ProjectContext if you selected Yes, or something like ExternalContext if you selected No.
<connectionStrings>
<add name="ProjectContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Database.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<add name="ExternalContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=C:\Programming\.Net\DataVisualization\Data\DataVisualization\App_Data\Database.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
Note that the actual syntax of the connectionString may be different in your app depending on settings used, but the key part is the |DataDirectory| reference vs the correct path. The path is what you'd need to modify.
The shorthand solution is this:
public class LinkedDataContext : DbContext
{
public DbSet<LinkedData> LinkedData { get; set; }
public LinkedDataContext() : base("DefaultConnection")
{
}
}
I was assuming it would take the default connection if there was no connection named after the context. The reason was that I did not get a error so the connections would have been fine. Yet without specifying a connectionString in web.config it just seem to take part of the default string, since it does find my database and throws in it's namespace and creates a new database out of thin air. I might be new to MVC but I find this ridiculous default behavior. So I still have no clue what the idea behind this is.
Unless you want to have a couple of hundred connection strings for a fairly sized application the only way to go seems to be to call the parent constructor and specify the DefaultConnection there. Kind of ironic you have to "specify" default behavior.
Unlike what #tomtom told me, in almost 10 hours I did not find a single scenario that resembles mine. Maybe I was not clear but in my initial post I did specify each step I took. Using a MSSQL SERVER does not seem to be necessary.
Hope this helps someone else out.
STANDARD BEHAVIOR. As bad as it is. Your db template is copied to the runtime every time you hit the "debug" button, so you always start with a new datababase. Painfull as hell. Not sure how other's solve this - I never use this side of visual studio, I have a sql server installed and create my databases there manually. Makes sure i am always working against a defined copy. Obviously VS has no rights to create databases there ;)
If you bother using google or the site search a little you find tons of similar questions - this is a standard problem people regularly get trapped in because it is totally not what they expect.
(if you ask me, the whole db maintenance side of EF is broken anyway, including the "migrations" that hardly can use SQL Server most basic features).

Connection string for MySQL missing in other projects

I am currently developing a solution with both an ASP.NET project, and a WPF application. I have a common project too, with an ADO.NET entity model, where entities are generated from a database.
If i try to call anything from my database (MySQL) from my WPF, ASP or a Test project i get a InvalidOperationException where it says that no connection string named "DataModel" could be found in application config file.
I then have to add entity framework connectionstrings and other stuff to each project, in order to be able to fetch data from my common project or database. It also means if i want to change the db connection i have to do it in every single project. Isn't there a smarter way to do this?
Thanks..
Isn't there a smarter way to do this You're doing what most people do, at least for small and medium environments, by putting the connection string in each project.
Most projects need different connection strings for different environments (DEV, QA, PRODUCTION). I use and highly recommend the free add-in Slow Cheetah. That tool allows you to define XSLT transforms to modify XML files in your project. In this case, I use it to drop in the correct connection string depending on the build settings.
When you are ready to create a build for the PRODUCTION environment, you just change the Visual Studio solution configuration to Release, and the generated web.config/app.config contains the PRODUCTION connection string.
You can pass the connectionstring that has to be used to the constructor of your DbContext. You have 3 options to pass a connectionstring:
Pass nothing, EF will look for defaultconnectionstring in configfile, if none is found it will throw an error.
Pass the name of the connectionstring you want to use, if it's not found in the config file EF will use the default connectionstring.
public partial class MyDb : DbContext
{
public MyDb(string connectionStringName) : base(connectionStringName)
}
Pas a connectionstring to the constructor. EF won't look in any config files and just use that one, this is probably what you're looking for:
public partial class MyDb : DbContext
{
public MyDb(string connectionString) : base(connectionString)
//Or hardcode it in:
public MyDb() : base("datasource=...")
}
Edit: It is indeed not good practice to do the above, I'm just saying it's possible.

Entity Framework on .mdf file

I am working on some project at the moment and I have to use local database. So, I created a new service-based database (no tables atm). Then I wanted to add Entity Framework support.
Because I never used Entity Framework before, I was referring to that link: http://msdn.microsoft.com/en-us/data/jj200620.aspx.
Everything is OK, but here it gets complicated. I created my DataContext class with DbSet inside it. But, when I run my unit test, table is created on Localdb (not inside my .mdf file).
What to do?
I am pretty sure, that I did choose which database to use correctly (actually did that 3 times already), but still, data tables are created on LocalDb. What I am doing wrong here?
I am complete beginner with that (been only using doctrine ORM). Otherwise I can insert data and all, it is just on the wrong database.
When your doing code first development in EF, you can force EF to only ever consider one connection string name.
One of the constructors (of which there are quite a few overloads) on the EF Data Context parent classes, takes a simple string.
This string is given to be the name of a connection string in the App or Web config to use.
You make the call something like this:
using System.Data.Entity;
namespace MSSQL_EFCF.Classes
{
public class DataAccess : DbContext
{
public DataAccess() : base("myConnectionString")
{}
public DbSet<MyTableObject> MyObjects { get; set; }
}
}
You can still put any code you need for your own start-up (Such as DB Initializer calls) inside your constructor, and all that will get called once the base call completes.
The advantage of doing things this way forces entity framework to always use the named connection string and never anything else.
The reason this catches many developers out, and why it runs off an uses localdb is deceptively simple.
The Entity Framework DbContext by default will use the name of the data context derived class as a database name, and if it can't find a suitable connection string in any config file by that name, makes the assumption that your working in development mode without a full backing data store.
In my example above, EF would examine App and/or Web.config for a connection string called "myConnectionString"
Once it makes this development decision, it knows that localdb will be present as this gets installed with the latest builds of visual studio, and so it will automatically seek out a connection and populate it with a db that follows the name of the context in which it's used.
I've previously written a blog post on the subject, which you can find here :
http://www.codeguru.com/columns/dotnet/entity-framework-code-first-simplicity.htm
NOTE: The above applies to any database that you connect with using EF, it's the connection string that decides what/where the actual data store is.

Entity Framework 5 Lost its Connection String

I have used EF5 for my project and I encrypted my connection string in project's web.config file.
And I replaced the constructor of Entities like this:
public PEntities()
// : base("name=PaypalEntities")
: base(Cryptography.DecryptConnectionString())
{
}
But when I want to update my database model with EF wizard, it asks to me for a new connection string and credentials and replaces my connection string in my config file with this. So my project doesn't run properly.
How can I solve this problem?
I'd strongly encourage you to have the Entity framework model in a separate project. If you do that, the project can have its own connection string that points to your reference database (the one you use for making changes as and when necessary). Thus, the running assembly, whether it be a web project or anything else, will just refer to the model project and can have its own connection string.
Yes...
The Solution is, Create a Partial class with same namespace and write the method into it.
Now whenever you update database or edmx file you will find it's default constructor. just delete it.
refer this
http://forums.asp.net/post/4722699.aspx
Try to uncheck the "Save entity connection settings" checkbox:

Moving Entity Framework model into class library from web project

I am using Entity Framework and recently came to realize the benefits of having your EF model in another project within the same solution so that I can build multiple UIs from it.
I moved it over to a new class library project and updated all the references to the entities in the web project to use the new dll generated by the project. Everything has gone smoothly, except for one small snag. When I moved EF over to the new project, somehow it was still reading its connection string from the web.config in the web project (don't ask me how because I have no clue).
I used "Update Model from Database" in the EF designer and it did not find a connection string (as I expected after moving it over to the new project) so I used the wizard to generate a new connection string, which it did just fine. The new connection string now resides in App.config within the class library project. The connection string in the properties window is correct now, and the designer is reading it from the App.Config. I went ahead and deleted the connection string from Web.Config in the web project.
Now when running the application I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
If I paste the connection string back into the Web.Config it all works just fine. I do not want to create a new EF model from scratch because it is a fairly complicated model and I did a lot of restructuring after pulling in from the DB. I have poured over the generated CS file as well as the XML in the edmx file and cannot find anything useful. Any help is much appreciated. Obviously for now, until I figure this out, I'm just leaving the connection string in web.config since, for whatever reason, that seems to work.
This is by design; while the config file in the class library is what the designer will use, the configuration file of the actual application is what will get used at runtime. Whether that's Web.config for an ASP.NET project or App.config for a Winforms or WPF project, it's the application configuration file (or something higher up, like Machine.config) that will be used; the file in the class library is not part of the application.
If you're trying to provide an EF model that will work without having to specify the connection string in the application or web configuration file, then you'll have to store the connection string some other way (you could always hard-code it) and pass it into the appropriate overload of your context's constructor.
My solution is generally to provide a static parameterless function on the context itself that calls this overload with the appropriate connection string.

Categories

Resources