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