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.
Related
Hi I have a windows Form Application and using Database First Approach. When I am trying to save data using following code its not showing any error but not saving data into my .mdf database.
Models.NorthwoodRetreatsDBEntities db = new Models.NorthwoodRetreatsDBEntities();
db.Treatments.Add(new Models.Treatment() {
Name=_name,
address=_address,
phone=_phoneNo,
Email=_emailAddress
});
db.SaveChanges();
Not showing error I am also trying see is it inserted using the following line of code
bool a = db.ChangeTracker.HasChanges(); //double check if there was any change detected by EF or not?
it is returning true and
int UserID = db.Treatments.Max(item => item.AccommodationID);
Always returning 1 but when I explore database table showing nothing there and also when I am adding second item "int UserID" again 1. Now I am just wondering that can I use Database First EF with Windows Form. Could you please advice.
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.
I've been messing around with changing my object properties, and that requires me to keep updating my table, but I keep getting errors, so does anyone know how I can just delete the whole DB and start over?
I have this code
using (var ctx = new Context())
{
foreach (Item2 block in new_Items)
{
ctx.items_db2.Add(block);
}
ctx.SaveChanges();
test = (from b in ctx.items_db2
orderby b.Index
select b).ToList();
}
I've tried truncating the table but I can't do that since I've changed the object properties, and even when I run the commands from the package manager console to update the table, I get other errors so I'd just like to start from a clean slate.
You can do it from from your code just by running:
using (var ctx = new Context())
{
ctx.Database.Delete();
}
Alternatively connect to your database using VS - View --> SqlServer Object Explorer connect to your database server, right click on the database you want to delete and select Delete. You want to check the checkbox to close existing connection otherwise deletion may fail.
If the migrations are not important, I:
Delete migrations.
Delete all the tables in the database.
Run the Enable-migration command.
Run the Add-migration command, to add an initial migration.
Run the Upgrade-database command. This will rebuild all the tables in the db, and you back to square one :)
I use code first.
We are getting ready for a big SQL migration.
Currently, I have the code written, and I am testing it out with data on my local machine.
Step 1 is to throw out the existing data in the table before I import the new stuff:
using (var txn = m_mySqlConnection.BeginTransaction()) {
using (var cmd = new MySqlCommand("TRUNCATE TABLE `blah_blah`;", m_mySqlConnection, txn)) {
cmd.ExecuteNonQuery();
}
// other code
}
But, the TRUNCATE command is throwing an exception whenever I try to execute it with the MySQL user account I am running the code with:
I tried going into MySQL Workbench to give this userid DROP permission, but all I could find was a way to add DROP under the View section.
I tried that, but it did not work.
How do I go about giving this user the ability to remove the data in these tables so that I can test my populate script?
TRUNCATE deletes the table. Try using DELETE FROM Table.
I'm looking to be able to dynamically create linked tables with C# in an accdb/mdb existing file. Is this possible? The idea would be for every linked table ALREADY in a given access database dynamically create a new linked table and then the second part of the problem would be to then rename name this newly created table to the pre existing table.
If its not already clear there is a migration going on from one database to another so every pre existing table has an equivalent table in the new database but they need to have the same name in the Access database in order for the queries to work etc.
Is this even possible?
EDIT:
I have created a test database that contains one linked table to an ODBC database. I have also created a simple query that just counts the rows. My C# code runs the query first and then attempts to change the connection string with the code:
var dbe = new DBEngine();
Database db = dbe.OpenDatabase(#"C:\Users\x339\Documents\Test.accdb");
foreach (TableDef tbd in db.TableDefs)
{
if (tbd.Connect.Length > 5)
{
if (tbd.Connect.Substring(0, 5).Equals("ODBC;"))
{
tbd.Connect = tbd.Connect.Replace("ODBC;DSN=ILACFEUC;UID=cloaseuc;DBQ=ILACFEUC;DBQ=W;APA=T;EXC=F;FEN=T;QTO=F;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS=F;MDI=F;CSR=F;FWC=F;FBS=64000;TLO=0;MLD=0;ODA=F;;TABLE=CLOASEUCDBA.T_BASIC_POLICY", "ODBC;DSN=ILACFEUC;UID=cloaseuc;DBQ=ILACFEUC;DBQ=W;APA=T;EXC=F;FEN=T;QTO=F;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS=F;MDI=F;CSR=F;FWC=F;FBS=64000;TLO=0;MLD=0;ODA=F;;TABLE=CLOASEUCDBA.T_BILLING_INFORMATION");
tbd.RefreshLink();
}
}
}
however it is not working. If I open the database up in access the connection string is unchanged?
It sounds like you really just want to change the external database to which the existing linked tables are connected. In that case you could do it in C# like this:
// This code requires the following COM reference in your project:
//
// Microsoft Office 14.0 Access Database Engine Object Library
//
// and the declaration
//
// using Microsoft.Office.Interop.Access.Dao;
//
// at the top of the class file
var dbe = new DBEngine();
Database db = dbe.OpenDatabase(#"C:\Users\Public\FrontEnd.accdb");
foreach (TableDef tbd in db.TableDefs)
{
if (tbd.Connect.Length > 10)
{
if (tbd.Connect.Substring(0, 10).Equals(";DATABASE="))
{
tbd.Connect = tbd.Connect.Replace("oldBackEnd.accdb", "newBackEnd.accdb");
tbd.RefreshLink();
}
}
}
db.Close();