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.
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.
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'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.
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();
Every time I do update-database -v -f I want my database to be fully dropped and then created empty again. Is it possible to do?
I tried to delete it and then create it but it doesn't work. Strange thing that I did exactly same thing in EF4 and it did work, but now it does not.
So how can I re-create my database using some command?
Migrations is enabled for context 'MainDataContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.
This is my seed method
protected override void Seed(Api.Models.MainDataContext context)
{
context.Database.Delete();
context.Database.Create();
// context.Database.Initialize(true); Also tried this but same result
}
Note: Truncate with raw queries does not work, too many relations.
Note: Delete all objects is bad idea, too many objects.
Could you perhaps first run the Update-Database like so:
Update-Database -TargetMigration:0
That would roll all migrations back to zero. And then run Update-Database again.
Edit: The seed method should not do anything to database structure, it should only modify the data. Migrations should be used instead.
Edit2: I can't find information on deleting the database with Update-Database, it will only rollback until first migration, which you seem to have none.
Only when deploying it through code, you can use DropCreateDatabaseAlways-strategy like so: http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
If you will do the migration manually, you'll probably have to manually remove the database before running Update-Database.
Do you want to drop and recreate the database when the model changes? How about...
Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
You are right, EF6 has changed the way migrations are handled.
You will have to delete your Migrations folder and all the classes in there.
#cederlof is right about update-database: there is not a drop database switch, or a create database switch. The only wan (AFAIK!) to create a EF6 database is to do new CloudMinderDataContext(someconnectionstring)
I had a problem because I wanted migrations to update my staging database but could not then create a new database in code. This was fine in EF4 but not in EF6. I had to use SQL to create database, then migrate it...
How do I generate an EF6 database with migrations enabled, without using update-database?
and
http://softwaremechanik.wordpress.com/2013/11/04/ef6-if-migrations-are-enabled-cannot-createdatabaseifnotexists/
Hi Steve: To drop one database use this. If you are integration testing your tests might actually run in parallel so be sure you've finished with this database before calling this...
private void DropDatabase(string connectionString)
{
var bld = new SqlConnectionStringBuilder(connectionString);
var dbName = bld.InitialCatalog; //database you want to drop
bld.InitialCatalog = "master";
var masterConnectionString = bld.ConnectionString;
using (var cnn = new SqlConnection(masterConnectionString))
{
using (var cmd = new System.Data.SqlClient.SqlCommand())
{
cmd.Connection = cnn;
cnn.Open();
cmd.CommandText = string.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE",
dbName);
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format("DROP DATABASE {0}",
dbName);
cmd.ExecuteNonQuery();
}
}
}