I have seen the other posts on this subject. Yet so far there has been no solution. I am working with Visual Studio 2013 in C#.
I have a database "Database1.mdf" with one table called Customers, which just has two records. I created the DataSet named CustomersDataSet (Menu: Project, Add New Data Source...) based upon this database.
This is my code.
CustomersDataSetTableAdapters.CustomersTableAdapter cta = new CustomersDataSetTableAdapters.CustomersTableAdapter();
CustomersDataSet ds = new CustomersDataSet();
// Fill our customersDataSetTable with the data from customers adapter
cta.Fill(ds.Customers);
Console.WriteLine("BEFORE");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
Console.WriteLine("\nMaking changes now...");
// Insert a new record
CustomersDataSet.CustomersRow newCustomer = ds.Customers.NewCustomersRow();
newCustomer.FirstName = "Brian";
newCustomer.LastName = "Faley";
newCustomer.City = "Denver";
newCustomer.State = "CO";
ds.Customers.AddCustomersRow(newCustomer);
// Update a record, [0] = gets access to the first row of the customers table
ds.Customers[0].FirstName = "Robert";
// Delete a record
ds.Customers[1].Delete();
// Update the dataset ds. Commit changes to the database
cta.Update(ds);
Console.WriteLine("\nAFTER");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
It works insofar as I do see the changes made to the dataset after "AFTER".
Yet I can run it as often as I wish - never are the changes written to the underlying database. The Update should do just that, but it does not. There is no AcceptChanges() in my code. I have followed up on all these suggestions - they do not lead anywhere.
Would someone have an idea?
I googled far and wide and all posts on this issue are unsolved.
When you debug the application the mdf file is copied to the bin\debug folder and your changes are committed to the database there.
Every time you start the project the mdf in the debug folder gets overwritten with the original database.
You can stop this behavior by going to the database settings in your solution and set the database to copy only if your version is newer.
Chances are your code was working all along.
Hope this helps.
Related
I have a database with three tables in it. I created all the tables within Visual Studio. My C# code is connecting to the database using Linq to SQL. The table I am having problems with is not updating on SubmitChanges().
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
tbl_Inventoryv2 inv = new tbl_Inventoryv2();
inv.Title = addTitleTextBox.Text;
inv.Model = addModelTextBox.Text;
inv.Category = addCategoryTextBox.Text;
inv.Quantity = int.Parse(addQuantityTextBox.Text);
inv.Price = decimal.Parse(addPriceTextBox.Text);
inv.Description = addDescriptionTextBox.Text;
db.tbl_Inventoryv2s.InsertOnSubmit(inv);
db.SubmitChanges();
int id = inv.IdInventory;
MessageBox.Show($"Item creation successful. Item number is {id}");
}
My database does have a primary key called IdInventory that is set to increment. Within the program, the correct increments are working as shown in my MessageBox statement above, but it never actually gets saved to the database. I have also checked the properties of the database file in Visual Studio and the path to the database is correct, as well as the Copy to Output Directory is set to Copy if Newer. Most of the questions I have looked up indicate that is usually the problem, but that doesn't look like the case for me. I am new to SQL and interacting with it via Visual Studio/c#, and SQL in general, so any input is greatly appreciated.
So I have a Database that I created a Dataset from, I'm attempting to run an Update on it and I cannot get it to update the Dataset (and subsequently the Database) with the result. I built the Query using Visual Studio's query builder and when I run it through there it changes the data in the way that it should. When I run the code I put in a MessageBox to show the number of rows the query changed and it is returning 1 as it should. I'm at a loss as to why it won't 'commit' the update and I'm sure I'm missing something very simple.
Here is the Query I setup (named "UpdateQuery")
UPDATE Bug_Master
SET Name = #Name, Test_App = #Test_App, Bug_Type = #Bug_Type, Bug_Active = #Bug_Active, Bug_Description = #Bug_Description, Bug_Keywords = #Bug_Keywords
WHERE (Id = #Original_Id);
In the Load event for the form I have
this.bug_MasterTableAdapter.Fill(this.bugManagerDataSet.Bug_Master);
And here is where I am calling the Query and trying to update (I know I should use 'using' but I'll pretty up the code after I get this to work so forgive the inelegance)
SqlConnection connection = new SqlConnection(strSQLConnectionString);
connection.Open();
int iResult = bug_MasterTableAdapter.UpdateQuery("Error One 1", "PassVault", "Runtime", "True", "Description Test", "Keywords Test", 1);
MessageBox.Show(iResult.ToString());
bug_MasterTableAdapter.Update(bugManagerDataSet.Bug_Master);
connection.Close();
As I mentioned above the MessageBox shows '1'. Is there a critical step I'm missing on how to do this? It has been a long time since I messed with SQL so I've had to bumble my way back to it and have no doubt I've missed/messed up some things.
Thanks in advance.
erik
Found the solution. Turns out the 'copy to output directory' property on the database file was set to 'always copy'. So when I ran the program it would make changes to the database in the \bin\debug folder while I was looking at the one in the app folder. Then when I would restart the program to check the values in there it would overwrite the changed version of the database in \bin\debug with the unchanged version from the project.
So, the upshot is for anyone else that runs into something similar is set the 'Copy to Output Directory' option on the database to 'Copy if Newer'.
Thanks to all who took a look.
erik
I must say - I am struggling with whole Database - Adapter - DataSet model.
Using Visual Studio 2010 (C#, .NET, WPF), I have created a local database (.sdf extension).
I added data source (Data > Add new data source) from my only table from my only database.
And from there, I cannot seem to properly update data into database. Here's what I'm stuck with:
private Random rnd = new Random();
private void button1_Click(object sender, RoutedEventArgs e)
{
PokerStatsDatabaseDataSet myDataSet = new PokerStatsDatabaseDataSet();
PokerStatsDatabaseDataSetTableAdapters.PlayersTableAdapter adapter = new PokerStatsDatabaseDataSetTableAdapters.PlayersTableAdapter();
adapter.Fill(myDataSet.Players);
Console.WriteLine(myDataSet.Players.Rows.Count);
foreach (PokerStatsDatabaseDataSet.PlayersRow r in myDataSet.Players.Rows)
{
Console.WriteLine("\t" + r.ID + " " + r.Nick);
}
PokerStatsDatabaseDataSet.PlayersRow row = myDataSet.Players.NewPlayersRow();
row.ID = rnd.Next(2, 1000);
row.Nick = "asdf";
myDataSet.Players.Rows.Add(row);
adapter.Update(myDataSet);
}
DataSetTableAdapter::Update should update data into database, but it fails to do so.
Every time the function runs, it properly prints the content of the database to console (including newly added rows) but after every application restart all changes are gone.
The database file "Copy to output directory" parameter is set to "Copy always" (honestly, I don't even know why).
Thanks in advance for your answers! Best regards!
#EDIT
I've found out that manually setting Connection.ConnectionString to full path solves the issue:
adapter.Connection.ConnectionString = #"Data Source=C:\Users\someUser\Documents\Visual Studio 2010\Projects\PokerStats\PokerStatsDatabase.sdf";
Before that change adapter.Connection.ConnectionString returns:
Data Source=|DataDirectory|\PokerStatsDatabase.sdf
It appears that DataDirectory substitution string was not correctly set by the DataSet Wizard.
After:
AppDomain.CurrentDomain.SetData("DataDirectory", #"C:\Users\someUser\Documents\Visual Studio 2010\Projects\PokerStats");
The code works fine too.
Now, what truly boggles me:
Why does the TableAdapter correctly fill the DataSet with data when it's not provided correct path? Why can't it update data with the same path it used to fetch data?
I am using Visual Studio 2012. I have a very simple Products table in a Local Database (cleverly named Database1). It has two fields: id and Name. I preloaded it with a few test data.
The following code should update the Name of the first Product. Internally, it does. I can retrieve all Products and see that the first one's Name is "Shirt." But the change is never flushed to the database. The record is never updated. Examining the database reveals that the name has not been changed.
My question is simple: Why are changes not being sent to the database?
using (var context = new Database1Entities())
{
var products = context.Products;
products.First().Name = "Shirt";
context.SaveChanges();
}
Thanks in advance.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
EDIT:
I tried my best to enter the full code and output here. But, no matter what I do, I continue to get the "Your post appears to contain code that is not properly formatted" error message. After 30 minutes I am giving up.
EDIT:
The code and output is here: http://pastebin.com/GmQtwAND
I discovered the issue...and its solution.
The "Copy to Output Directory" property of the database file was set to "Copy always." This, of course, meant that every time the application was built, a fresh copy was placed into the Bin directory. The fix was to set it to "Copy if newer." Doh.
In other words, the changes were being persisted in the database, but then the database was being clobbered when the application got rebuilt.
Well this could mean that you're not tracking changes, how about you try to set the State to -> Modified and see if it's going to work:
var product = products.First();
product.Name = "Shirt";
product.State = EntityState.Modified;
context.SaveChanges();
If you want to enable it for the context you can do it like this:
context.Configuration.AutoDetectChangesEnabled = true;
I'm taking a class in C# web dev and I'm currently trying to display data from a .mdb (Microsoft Access) database. I have two pages that both want to show a table stored in the database in a grid view. One page's form uses function that connects the the db and then writes to the table to the grid. it connects with this call:
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
sqlDA = new OleDbDataAdapter("select * from tblPersonnel where LastName = '"+strSearch+"'", sqlConn);
//Initialize a new activity
DS = new dsPersonnel();
//Add rows to the dataset from the data source
sqlDA.Fill(DS.tblPersonnel);
The database is called PayrollSystem_DB.mdb. In the other page I placed a SqlDataSource control on the page and connected it to PayrollSystem_DB.mdb. Then set this to the gridView. However when running, the the first page shows a long table with data I've entered since last week. and the 2nd page shows only data from the first day I tested it. Looking at the db in the vs explorer the tables are identical to teh second page.
So I'm wondering were all the other data is being stored that the first page is showing? Am I unknowingly using a database I can't see in the solution?
Just a guess, but have you tried clearing your browsers cache and then looking at the first page again? Try that. If the data is still showing I would compare the size of the MDB before and after an insert to see if the MDB grows. If not, try a search of all the files on your PC limiting it to only files modified recently, I think that will at least help you find where the data is being stored.