Getting a DbUpdateConcurrencyException after deleting all data from database - c#

My senario is: We have a production and an integration database and I wrote a tool to migrate some of the data of the production database to the integration database. For this I use: Entity Framework 6.0, .NET-Framework 4.5.2 and the databases are MS SQL Server Standard (64-bit) 13.0.5102.
My problem: While saving the deletion of all data in the integration database, the SaveChanges method throw an DbUpdateConcurrencyException with the error message
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded.
The following is the code that through the exception:
using (var prod = new DbProdContext())
{
using (var #int = new DbIntContext())
using (var transaction = #int.Database.BeginTransaction(IsolationLevel.Serializable))
{
try
{
var stack = BuildStack(#int, ...); // buikds a stack of the tables where the latest pushed tables depdend only on already pushed tables
// Deleting everything in db
using (var x = log4net.NDC.Push("Deleting old content"))
{
foreach (var table in stack.Reverse())
{
var destSet = table.DestSet;
destSet.RemoveRange(destSet);
}
log.Info("Saving Changes...");
#int.SaveChanges(); // <-- throw exception
log.Info("Completed Saving Changes");
}
// code to insert the data
transaction.Commit();
}
catch (Exception ex)
{
// log
transaction.Rollback();
}
}
}
Note: The variable stack is a stack of the table in the integration database where for any given table t all table which t depends on are pushed onto the stack before t is pushed onto the stack.
Seoncond note: I tested the code with migration the data from a local test clone of the production database into the integration database which never throw this exception.
Does any body know how to prevent this error or what caused it.
Third note: The integration database it currently note in use to there could not be a concurrent change to the database from a different process.
Should I maybe just create sql drop statements for the tables instead of using destSet.RemoveRange(destSet)

Should I maybe just create sql drop statements for the tables instead of using destSet.RemoveRange(destSet)
Yes. You should do that. But if you don't want to recreate the tables, it should be DELETE or TRUNCATE TABLE instead of DROP TABLE.

Related

No rows found in update scripts when trying to update a inserted record on the same ReadCommitted Transaction in C# and SQL Server

I'm using C# 4.0 and SQL server 2016. Also using ADO.Net Inline query to insert and update details.
Here is the sample code i am using:
TransactionOptions txOpt = new System.Transactions.TransactionOptions();
txOpt.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, txOpt))
{
int uniqueValue = InsertRecordInDB("Hi","Hello"); //returns 1
UpdateRecordInDB(uniqueValue,"Bye"); // sometimes update return no row found.
scope.Complete();
}
Sometime the update method is returning no row found. Multiple calls will be made to this method at the same time from various users.
Am i missing something or is there any error in my code?

Linq to SQL not saving to database on SubmitChanges()

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.

Completely delete EF database in c#

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.

DROP command denied to user X for table 'Y'

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.

dynamically create link tables and rename them in access 2007/2003 with c#

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();

Categories