I found a solution that must be for a older version then vs2010. I would like to know how to do this for vs2010? Does anyone know?
http://www.csharpbydesign.com/2008/01/overriding-dataset-settings-co.html
Let me explain little more detail.
I have a c# generated dataset. How can I change the connection string so I can use the dataset with another (identically structured yet differently populated) database? This has to occur at runtime as I do not know the server or database name at compile time. i AM USING vs2010 and SQL Server 2008 R2 Express
I think there is no simple way and you cannot change the Connection-String programmatically for the entire DataSet since it's set for every TableAdapter.
You need to use/create the partial class of the TableAdapter to change the connection-string since the Connection property is internal (if your DAL is in a different assembly). Don't change the designer.cs file since it will be recreated automatically after the next change on the designer. To create it just right-click the DataSet and chose "show code".
For example (assuming the TableAdapter is named ProductTableAdapter):
namespace WindowsFormsApplication1.DataSet1TableAdapters
{
public partial class ProductTableAdapter
{
public string ConnectionString {
get { return Connection.ConnectionString; }
set { Connection.ConnectionString = value; }
}
}
}
Now you can change it easily:
var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;
Here's a screesnhot of my sample DataSet and the created file DataSet1.cs:
There's actually a much easier way to change the connection string.
Go to the Settings screen, where the connection string is displayed as a connection string.
First mark and copy the connection string that's displayed.
Then change the type from connection string to string. The text for the string will change to include xml.
Then paste the copied connection string over the xml text.
Then change the scope from Application to User.
When I want to change the connection string, I use the following code.
// assign the path to use to the variable fullpath (or whatever)
string newConnection = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", fullpath);
Properties.Settings.Default.HootConnectionString = newConnection;
Properties.Settings.Default.Save();
In my case, I have a global Dataset active, so I have to make that the data is reread by the tableadapter. And, of course, you'll have to add error control to make sure the database is still there.
You'll notice that this will not change what is displayed in Application Settings. Those are defaults.
This works for an Access database; so your mileage and requirements may vary.
EDIT: Caveat. As it works out, when installed, the connection string works well for opening and reading database content, but it complains about not having a connection string when trying to update a database.
Related
I am developing an WPF application with EF 6 database first approach, I am have 1 project in my solutions, if i run my project this error always appear.
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. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
My mistake was using standard connection string in constructor
(Server = test\test; Database = DB; User Id = test_user;Password = test),
but Entity Framework needs different format
(metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=test\test;initial catalog=DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""" providerName = ""System.Data.EntityClient)
Edit: Changed code to be formatted as code so it's easier to read.
EF makes assumptions based on the presence or absence of a metadata section in the connection string. If you receive this error you can add the metadata section to the connection string in your config file.
E.g. if your connection string looks like this:
<add name="MyModel" connectionString="data source=SERVER\INSTANCE;initial catalog=MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Prepend metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl; so that it looks like this:
<add name="MyModel" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;data source=SERVER\INSTANCE;initial catalog=MyModel;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
One thing you can do is... (if is Database first)
Open the .edmx[Diagram] -> right click -> "Update Model from database"
And see if the will appear the "Add", "Refresh" and "Delete" tabs.
If doesn't... probably your connection is broken and the dialog for VS creates a new connection string will appear instead. =)
You shouldnt use generated connection string, now you have all metadata files included in your solution. Instead try use in connection string section of app.config:
"data source=localhost\sqlexpress; initial catalog=sample; integrated security=True;MultipleActiveResultSets=True;"
None of the above solutions worked for me. But I did find the SqlConnectionBuilder class here which did work: https://learn.microsoft.com/en-us/dotnet/api/system.data.entityclient.entityconnectionstringbuilder?view=netframework-4.8
Its the same as specifying the string as some of the other suggestions here but it builds the string for you.
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = ".";
string databaseName = "AdventureWorks";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/AdventureWorksModel.csdl|
res://*/AdventureWorksModel.ssdl|
res://*/AdventureWorksModel.msl";
Console.WriteLine(entityBuilder.ToString());
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Console.WriteLine("Just testing the connection.");
conn.Close();
}
I also faced this exact same message, but workig with a web MVC project. This message is fired when I try to auto generate the Controller from the imported model. It seems that it is not working because "that was generated from an EDMX file".
The good news is that it works if I generate the model based in the "Code First" instead of "EF Designer". The bad news is that I can't use the EF Designer if I want that the automatically controller generation works. Does not matter which from those two ways you generates your model. Once the model is generated, you use it in the same way.
Tries to remove all your emdx objects from your project and recreate the model based in the Code First instead of EF Designer. Worked for me!
Very much late but still helpful. I got stuck in a similar problem. Posted a question about on SO and was able to find a solution. You can refer to Connection String errors in C# Web Api.
My situation was I had two connection strings in web.config (you'll get to know why when go to the link). Commenting one string was raising the error you got while commenting the other one was raising error as below:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.
what i did was: I named my first connection string as DefaultConnection and in ApplicationDbContext class constructor I gave this DefaultConnection. Now my AccountController uses this connection string and all other controllers use second connection string.
This solved my problem.
I have two projects:
One is for the generated EDMX file and all related models.
The other one is the ASP.NET MVC Web.
I encountered this issue since the connection string that I am using on the ASP.NET MVC Web project is the normal string that I use using ADO.NET connection. So what I did is the following:
Open the app.config on your EDMX project files.
Copy its connection string.
Paste it on the WEB project since this will be used when you start
the application.
Here is everything that I did:
In a visual studio 2013 C# project, I created a service database (.mdf file). Note: I changed the name from Database1.mdf to fghLocalDB.mdf.
I opened this database in the server explorer.
I created 2 tables called Country and CarbonDioxide using the table designer.
I added an entry to the Country table as shown by the Data Table of the Country table.
I did the following to create a DataSet my application can use. I created a Data Source by clicking on the "Project" option on the top menu bar and clicking on the "Add New Data Source ..." option from the drop down.
This is what my project files looked like at this point.
I wrote the following code in the main method thinking that this would be all I need to write to the database.
// Create a connection to the DataSet and TableAdapters that will communicate with our
// local database to handle CRUD operations.
fghLocalDBDataSet dataSet = new fghLocalDBDataSet();
fghLocalDBDataSetTableAdapters.CountryTableAdapter countryTableAdapter =
new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
try
{
// Insert a row into Country table. EDIT 1 Will comment after first program run.
Console.WriteLine(countryTableAdapter.Insert("United States"));
// Actually writeback information to the database?
// dataSet.AcceptChanges(); EDIT 2 commented this as LeY suggested it was not needed.
// EDIT 3 Validation code as suggested by Ley.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
adapter.Fill(dt);
foreach (var row in dt)
{
// This does not get executed after a second run of the program.
// Nothing is printed to the screen.
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
}
catch(SqlException exception){
Console.WriteLine("ERROR: " + exception.ToString());
}
Console.ReadLine();
I ran the program and everything seemed fine.
I opened the tables by right clicking on these tables in the server explorer and pressing "Show Data Table".
The "United States" row was not added as wanted.
I think it has to do with the connectionstring. I right clicked on my project and opened properties.
Here I made sure the connection string matched that of the local database by looking at the string in the properties of the database. They are the same.
I copied and pasted the actual text for each connection string:
Connection string of project:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Connection string of actual database (.mdf file):
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
I am assuming |DataDirectory| is equal to C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf; since in the picture above when I clicked on the button to expand the Value of the connection string the connection properties window opened up and had this path for the database file name.
My question in a nutshell is does instantiating a DataSet object in the code automatically create a connection to a SQL service-based database for CRUD operations?
If not how do I connect my DataSet object to my sql database so that way I can actually write to the database when using the TableAdapters?
I read the following links:
Insert method of TableAdapter not working?
TableAdapter Insert not persisting data
Use connectionstring from web.config in source code file
Do I need an actual SqlConnection object? and how to I connect this to the DataSet & TableAdapters?
I never used tableadpter.insert() method. But I tried it on my local machine, and it works.
I can't figure out your problem based on the information you provided, sorry, but I can point you a direction.
If you created everything from wizard, you don't need to worry about the connection, the table Adapters will handle the connection for you. The connection string (you circled) will be added to your app.config file as well as your setting class automaticly. That is how your application (or you) uses it.
var countryTableAdapter = new CountryTableAdapter();
countryTableAdapter.Insert("United States");
This 2 lines of code are enough to insert the row into database if there is no exception thrown, I don't know why it doesn't work for you. Maybe the way you verify it somehow goes wrong, but you can verify it in another way.
The countryTableAdapter.Insert method will return the number of row get affected, in your case , should be one. So put the following code in , and set a breakpoint after it. if the rowAffected == 1, then the insertion works.
var rowAffected = countryTableAdapter.Insert("Test2")
If you need more confirmation , try this.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new CountryTableAdapter();
adapter.fill(dt);
foreach (var row in dt){
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
you will see all the records in your table.
I hope this will help.
By the way, from your code
dataSet.AcceptChanges();
The line of code above doesn't update the database at all. It only modify your local data storage.
it overwrites your dataRow original version using current version and change the current version row state to unchanged.
Only the tableadapters can talk to database (not true I know, but I just want to make a point that Dataset can not talk to database directly).
And I usually only need tableadapte.Update method and pass the dataSet or dataTable in with correct RowState.
The tableAdapter.update method will call AcceptChanges on each row eventually if it successfully updated the database.
You should never need to call AcceptChanges explicitly unless you only want update your dataset in memory.
I recommend you to read ADO.NET Architecture to get the big picture how DataSet and TableAdapter worked.
It was my connection string after all. In my original post, I said I had two connection strings:
Connection string in project settings:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Actual connection string in fghLocalDB.mdf file:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
Something went wrong with
|DataDirectory| = C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;
in my App.config.
My Solution:
What I did was copy the actual connection string of the .mdf file from the .mdf properties panel and paste it into the project properties => Settings => Value field of the connection string set up.
Afterwards I ran my code again and sure enough the data persisted in the tables.
I did not need dataSet.AcceptChanges(); as #LeY pointed out. I also did not need a TableAdapter.Update(dataset) call as posted in other solutions. I just needed the TableAdapter.Insert("...") call.
EDIT: ALSO Most importantly to answer my original question, instantiation a DataSet does not create a connection with the local database. Instead instantiating a TableAdapter does establish a connection with the database!
Here I need to get a string that identifies the database client using PostgreSQL with C#. Here is the following example.
Example:
private static void OpenNpgsqlConnection(string connectionString)
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("WorkstationId: {0}", connection.WorkstationId);
}
}
Error:
'Npgsql.NpgsqlConnection' does not contain a definition for 'Workstationid'.
You seem to mean the MS SQL specific property WorkstationId of SQLConnection.
This is an MS SQL specific property. It does not exist for nPgSQL, though of course you could add it.
The documentation in MSDN is profoundly useless, so it's hard to tell what it's actually for. At a wild guess, I think you probably mean something like PostgreSQL's application_name - a way for the server to find out information about the client from within a stored procedure or function.
client drivers or applications have to set application_name; there's nothing that gets set automatically to the "network name". (What would that even mean if the client was not a Windows box?). Your application could set application_name, either in the connection string or via an explicit SET command.
You can also run arbitrary SET commands. E.g you might decide to store the "workstation name" in the myapp.workstationid connection property. So you:
SET myapp.workstationid = 'BOBSCOMPUTER';
from your app, after making the initial connection.
Stored procedures can now access it with current_setting('myapp.workstationid').
Note that in both cases, a user with the ability to send raw SQL can just replace these settings with whatever they want. So don't use them for security.
I have developed a WinForm C# app that use ADO.NET Entity Framework for storing data.
I would like each user to have a database stored in their appdata\local folder but when I try to add the connection string to the users local app.config file I constantly get the error "ConfigurationSection properties cannot be edited when locked."
After I did some research I discovered the allowExeDefinition section setting.
I tried adding this setting for the connectionString section in the app.config file and at runtime (see code below) but I still get the same error whenever I try to save the configuration.
This is the code I use:
var connectionString = string.Format(ConnectionStringBase, dbLocation);
var exeConf = ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
var connectionStringSettings =
new ConnectionStringSettings(
"DatabaseEntities",
connectionString,
ProviderName);
exeConf.ConnectionStrings
.SectionInformation
.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
exeConf.ConnectionStrings.ConnectionStrings.Add(connectionStringSettings);
exeConf.Save(ConfigurationSaveMode.Minimal);
I have tried to search for a solution for this issue for days but I haven't been able to find anything usefull besides that I am considering storing the connection string in the users settings instead as a workaround but it feels kinda hackish.
Alright, instead of updating the app.config file I decided to create the connectionstring on runtime and pass it to the entity set constructor.
So when I initialize the entity set I use the following code instead:
var connectionString = string.Format(ConnectionStringBase, dbLocation);
var entities = new DatabaseEntities(connectionString);
The only thing to note is that if the connection string contains " you should replace these with single quotes ( ' ).
I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?
Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later
Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."