Entity Framework add failed but sql script is okay - entity-framework-6

I'm using Entity Framework to add new record, I can capture the insert SQL in SQL Server Profiler, but cannot find the new record in the database table.
When I copy the SQL captured and run it, I can get the record in the database table.
Question: why can I not find the new record in database table when adding it using Entity Framework?

Just found the reason. It is not about entity framework but about Nservicebus. The Handler can roll back when cancelling debug even db Savechanges() is invoked.

Related

EF 6 Code First Migration after deleting data from __MigrationHistory table

I have accidentally deleted data from __MigrationHistory table and I tried to make migration new tables and column changes to db. At this time EF6 show me an error
"There is already an object named 'xxxx' in the database.".
I tried the way by using this command and there is no effect on table column changes.
Add-Migration MyMigration1 -IgnoreChanges
Update-database -Force
There are many recommendation about this for recreating db or another else. But those ways might be effect data losing to my db which contains a huge size of tested data and I can't able to lost any data. How to solve this error by without losing any data. If anybody please...
Update
Finally I found the solution to solve my problem. I am not sure it's a prefer way to solve such kind of problems but it's worked for me.
I cleaned data from __MigrationHistory table,tried to migrate new db and I copied data from __MigrationHistory of new db to my old db, then I set AutomaticMigration true and run update-database command and the problem was solved.
I'm not sure if its good approach to fix that but it worked for me.
I just did insert into that table with proper version and names of the already applied migrations, I did it in EF Core and it works actually, but please wait for somebody to comfirm that what im writing about.
The problem I see there is that you need two more fields to be filled (in EF Core theres only two columns) but I think that you can receive them using for example SQL Profiler

Entity Data Model wizard disappears SQL Anywhere 17

I am trying to make a new model using Entity Framework 6 and SQL Anywhere 17. I followed exactly these steps.
http://dcx.sap.com/index.html#sqla170/en/html/37fb9e8558e94547b66156b9298be16f.html
But when I go through Entity Data Model wizard, it disappears after the following screen.
I got same Issue and able to resolve by following these step.
Open server explorer tab-
Delete all existing data connections-
Rebuild your project-
After this Entity Data Model wizard will not disappears.

Godaddy wont take database names with periods in them. MVC EF models need renaming how?

I created the databases first, then used the wizards in Entity Framework 5 to create the models from the Database first. Over time, through development, I made changes to the models and let EF recreate them by deleting my database and then starting the project up and they magically appeared again with the changes I made to the columns . It worked great on SQL Express 2014. But Godaddy doesnt let EF do that, AND I have databases with names like "Hazards.Models.CompanyDataContext" that EF made and didnt ask me what I wanted to name them. How do I change the code so it will let me rename the database it uses, and if possible, incorporate it into the aspnetdb that mvc uses as an additional table (there already is simplemembership etc. in there.)?
Seeing as you used EF database first, rather than deleting your database and letting EF recreate it, have you thought about doing it the other way round?
You could use something like management studio express to rename your database tables/columns however you see fit. Then in Visual Studio, open your .edmx file, right-click the background and select 'update model from database'. This way you can add new tables to the model or update the models of existing tables from the database. Better still, you can take care of it all outside of godaddy.
Note: I found that when updating the EF model, just updating existing tables gives odd results sometimes. It's much more reliable when you delete tables from your .edmx first, then right-click and select 'update model from database', and add the tables back to your model.

How to re-create database for Entity Framework?

I have got into a bad state with my ASP.Net MVC 5 project, using Code-First Entity Framework. I don't care about losing data, I just want to be able to start fresh, recreate the database and start using Code-First migrations.
Currently I am in a state where every attempt to Update-Database results in an exception being thrown or getting an error message. Also the website can't access the database correctly. How can I wipe all migrations, re-create the database and start from scratch without having to create a new project? In other words, I want to keep my code but drop the database.
Later I will also want to get the deployment database (SQL Server on Azure) in sync. Again, I don't mind dropping all the data - I just want to get it working.
Please provide any how-to steps to get back to a clean state. Much appreciated.
Follow below steps:
1) First go to Server Explorer in Visual Studio, check if the ".mdf" Data Connections for this project are connected, if so, right click and delete.
2 )Go to Solution Explorer, click show All Files icon.
3) Go to App_Data, right click and delete all ".mdf" files for this project.
4) Delete Migrations folder by right click and delete.
5) Go to SQL Server Management Studio, make sure the DB for this project is not there, otherwise delete it.
6) Go to Package Manager Console in Visual Studio and type:
Enable-Migrations -Force
Add-Migration init
Update-Database
7) Run your application
Note: In step 6 part 3, if you get an error "Cannot attach the file...", it is possibly because you didn't delete the database files completely in SQL Server.
I would like to add that Lin's answer is correct.
If you improperly delete the MDF you will have to fix it. To fix the screwed up connections in the project to the MDF. Short answer; recreate and delete it properly.
Create a new MDF and name it the same as the old MDF, put it in the same folder location. You can create a new project and create a new mdf. The mdf does not have to match your old tables, because were going to delete it. So create or copy an old one to the correct folder.
Open it in server explorer [double click the mdf from solution explorer]
Delete it in server explorer
Delete it from solution explorer
run update-database -force [Use force if necessary]
Done, enjoy your new db
UPDATE 11/12/14 - I use this all the time when I make a breaking db change.
I found this is a great way to roll back your migrations to the original db:
Puts the db back to original
Run the normal migration to put it back to current
Update-Database -TargetMigration:0 -force [This will destroy all tables and all data.]
Update-Database -force [use force if necessary]
This worked for me:
Delete database from SQL Server Object Explorer in Visual Studio.
Right-click and select delete.
Delete mdf and ldf files from file system - if they are still there.
Rebuild Solution.
Start Application - database will be re-created.
While this question is premised by not caring about the data, sometimes maintenance of the data is essential.
If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name
Apparently... a moderator saw fit to delete my post so I'll paste it here:
How to recover from Entity Framework nightmare - database already has tables with the same name
Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.
Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.
Error Message: System.Data.SqlClient.SqlException (0x80131904): There
is already an object named '' in the database.
Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.
To understand this in more detail, I'd recommend watching both videos referenced here:
https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx
Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.
Step 1: Production DB clean
First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts.
Open your production database and delete/drop the dbo.__MigrationHistory table.
Step 2: Local environment clean
Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.
Step 3: Recreate Initial
In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts).
Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code.
If you had any seed operations in the previous Configuration.cs, then copy that across.
Step 4: Trick EF
At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.
Step 5: Update-Database
With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like.
Now, uncomment that code and save.
You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.
Step 6: Confirm EF is ACTUALLY up to date
If you had code that hadn't yet had migrations applied to it, this is what I did...
Run "Add-Migration MissingMigrations"
This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.
Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.
Step 7: Re-confirm and commit.
Build, test, run. Ensure that everything is running then commit the changes.
Step 8: Let the rest of your team know how to proceed.
When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.
Just want to add to the excellent answer of #Lin:
5) B.
If you don't have SQL Management Studio, go to "SQL Server Object Explorer".
If you cannot see your project db in the localdb "SQL Server Object Explorer", then click on "Add SQL server" button to add it to the list manually. Then you can delete the db from the list.
A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.
My solution is best suited for :
- deleted your mdf file
- want to re-create your db.
In order to recreate your database you need add the connection using Visual Studio.
Step 1 : Go to Server Explorer add new connection( or look for a add db icon).
Step 2 : Change Datasource to Microsoft SQL Server Database File.
Step 3 : add any database name you desire in the Database file name field.(preferably the same name you have in the web.config AttachDbFilename attribute)
Step 4 : click browse and navigate to where you will like it to be located.
Step 5 : in the package manager console run command update-database

MVC Code First Connection String. I changed it. How do I reinitialize the database?

I mean I was using a .SDF file but then had issues getting that to work with my host. So then I went back to the SQL DB I already have but I noticed that when I go to the default MVC 4 index page it is looking for that entity that I already created when I used the original DB.. but this table does not exist with the new SQL DB I switched to..
I already verified that is is pointing to the new DB buy setting the connection string in the constructer.
How do I tell the code to 'RE CREATE THE TABLE' before trying to use it ?
If I understand your question correctly, you're looking for something like Entity Framework Migrations: http://www.hanselman.com/blog/EntityFrameworkCodeFirstMigrationsAlphaNuGetPackageOfTheWeek10.aspx

Resources