Do I use Snapshot file, migration file or data annotations in my EF Core to update database? - asp.net-core

I'm trying to understand the different types of migration paths we can choose when developing an ASP.NET Core 1.0 application with EF Core. When I created my first Core application I noticed it generated a ApplicationDbContextModelSnapshot class that uses a ModelBuilder to build the model.
Then I read that if I need to add a table to the database, I need to create the new model and run the command line to generate the migration file and update the database. Ok, I get it up to this point.
But when I do that, I notice that the ApplicationDbContextModelSnapshot class gets updated too.
1) Does that mean I cannot modify this ApplicationDbContextModelSnapshot class since it looks like it gets regenerated each time?
2) Should I use Data Annotations to build my model or should I use Fluent API which tells me to build my model in the ApplicationDbContext class? Huh? another file that builds the model?
I'm seeing three different ways of working with the database here, the snapshot class, data annotations, and fluent API. I'm confused because today, I made a mistake in my last migration file so I deleted the file, dropped the database and reran the database update.
But by doing that I got errors similar to:
The index 'IX_Transaction_GiftCardId' is dependent on column 'GiftCardId'.
ALTER TABLE ALTER COLUMN GiftCardId failed because one or more objects access this column.
So naturally I was wondering if I had to modify the ApplicationDbContextModelSnapshot class.
What is the path I should be taking when it comes to migrations or database updates because these three paths are confusing me.

I have run into this issue before when I create migrations, make model changes, create new migrations, and try to update the database. The root cause is when keys are being changed and relationships are not dropped and are not added back or do not exist.
You have two options
Easy Method
The easiest way is also the most destructive way and only possible in a dev environment.
Delete all migrations, drop the database, create new migrations and run 'update-database'.
Hard/Safest Method
This is the most time consuming method. I recommend do this in a local integration branch first, pushing it to a remote integration, and then production.
Open the migration file, ie 20160914173357_MyNewMigration.cs.
Drop all indexes in order
Drop/Add/Edit table schemas
Add all indexes back.
For either method, just be sure to test and test again.

Do not modify ApplicationDbContextModelSnapshot. It is a design-time artifact, and should only be modified in the case of a merge conflict.
To update the model, always use data annotations or the fluent API.
For more information on the EF Migrations workflow, see Code First Migrations. It's for EF6, but most of the information is still relevant.

Related

Proper way to work with migrations during development

How to properly work with migrations during development when the model is not in its final form or there are still some inconsistencies in relations?
Should migrations be treated more as commits in version control system like git and represent even the smallest change, or what?
Should I add new migration for each small change in my model, or should I just re-create the database and initial migration until I'm satisfied with how my model looks? I can still remove all those migrations in the end and create initial one to clean those small migrations up.
How to properly name migrations? Most often I can't come up with a good name and I give them some meaningless names like X1, X2, X3
Similar questions:
How to deal with database changes during development with EF Core?
1: I personally would keep it as a history. Of course you could always delete all migrations and create one that contains everything but imagine that migration after you have added 100++ tables (entity-types) and you cannot make sure your production database for instance is being updated, when you only have one migration with same name that you just always recreate.
2: Yes, you should indeed make small migrations. You can undo a migration by updating your database to a specific migration and then removing all the others before step by step. This at least works with the package-manager-console tool (maybe also with dotnet tool).
For instance you have already added a migration with models that have changed you go back to the old migration by using this command:
Update-Database -Migration MyMigrationBeforeBadModelMigration
Be aware that this might drop tables if some were added in the migration that you want to undo.
Then remove bad migrations step by step
Remove-Migration // will always remove the latest migration so repeat that if you have many to remove
Then just create the new and proper migration and update your db.
3: Yes, give them proper names. For instance CustomerEntityAdded or CustomerUniqueNameIndexAdded.

Completely disable EF6 Migrations

We have a Web Forms app using VB.NET. When we first started the project a couple years ago, we though DB Migrations was a great idea! However, the actual use of it was not as grand. So we tried to disable it. We followed the steps as outlined in the dozen or so articles including:
Remove the Migrations folder
Remove the __MigrationHistory table
added Database.SetInitializer(Of MyContext)(Nothing) to the constructor of MyContext
I have not found any form of "Disable-Migrations", only re-enabling migrations with more parameters which makes new config files and reinitializes migrations.
Even with all of this, EF keeps querying the database for the __MigrationHistory table which it can't find, so throws an error Invalid object name 'dbo.__MigrationHistory'.
How can we completely remove Migration History so EF stops using it?

RavenDb Config and DocumentStore abstraction?

I am using RavenDb across multiple projects and solutions to access three different databases that are all part of the same product. For instance, I have multiple MVC projects that fetch user info and some data out of the 'web' centric database and the 'backend' database, using '-' for the id override (but I need this only for a subset of classes in the 'web' db). And then I have another 'backend' database that is used by services (as well as the MVC projects). And finally a third temp/scratch database I use by another set of services to build the backend db. And of course, all of these are being accessed from different class libraries and even console test, seed, and integration test apps.
Managing all of these is becoming quite a nuisance. Every time I create a new console app or class library that access the db, I have to setup config and raven packages for each project, make sure indexes are built, etc.... Not to mention running update on all nuget updates, or in my case, installing a new unstable version of the server/client binaries.
Is there an easier way to manage this?
I tried to abstract the DocumentStore creation and initialization, as well as index creation into it own project and reference that. But the other projects then had to manually add newtonsoft.json (and nlog) from the package directory.
As well, I am getting the following when I try and abstract the DocumentStore into a class with a static property:
StackTrace of un-disposed document store recorded. Please make sure to dispose any document store in the tests in order to avoid race conditions in tests.
Anyone have any thoughts on handling these issues?
Thanks
I don't think that the manual addition of the references is a big issue, but you can add the actual nuget references as well.
Note that the DocumentStore not disposed error is something that only happened in the unstable (debug builds), and won't happen on release builds.

Rails: Best practice for handling development data

I have the following scenario:
I'm starting development of a long project (around 6 months) and I need to have some information on the database in order to test my features. The problem is that right now, I don't have the forms to insert this information (I will in the future) but I need the information loaded on the DB, what's the best way to handle this? Specially considering that once the app is complete, I won't need this process anymore.
As an example, lets say I have tasks that need to be categorized. I've begun working on the tasks, but I need to have some categories loaded on my db already.
I'm working with Rails 3.1 btw.
Thanks in advance!
Edit
About seeds:I've been told that seeds are not the way to go if your data may vary a bit, since you'd have to delete all information and reinsert it again. Say.. I want to change or add categories, then I'd have to edit the seeds.rb file, do my modifications and then delete and reload all data...., is there another way? Or are seeds the defenitely best way to solve this problem?
So it sounds like you'll possibly be adding, changing, or deleting data along the way that will be intermingled amongst other data. So seeds.rb is out. What you need to use are migrations. That way you can search for and identify the data you want to change through a sequential process, which migrations are exactly designed for. Otherwise I think your best bet is to change the data manually through the rails console.
EDIT: A good example would be as follows.
You're using Capistrano to handle your deployment. You want to add a new Category, Toys, to your system. In a migration file then you would add Category.create(:name => "Toys") or something similar in your migration function (I forget what they call it now in Rails 3.1, I know there's only a single method though), run rake db:migrate locally, test your changes, commit them, then if it's acceptable deploy it using cap:deploy and that will run the new migration against your production database, insert the new category, and make it available for use in the deployed application.
That example aside, it really depends on your workflow. If you think that adding new data via migrations won't hose your application, then go for it. I will say that DHH (David Heinemeier Hansson) is not a fan of it, as he uses it strictly for changing the structure of the database over time. If you didn't know DHH is the creator of Rails.
EDIT 2:
A thought I just had, which would let you skip the notion of using migrations if you weren't comfortable with it. You could 100% rely on your db/seeds.rb file. When you think of "seeds.rb" you think of creating information, but this doesn't necessarily have to be the case. Rather than just blindly creating data, you can check to see if the pertinent data already exists, and if it does then modify and save it, but if it doesn't exist then just create a new record plain and simple.
db/seeds.rb
toys = Category.find_by_name("Toys")
if toys then
toys.name = "More Toys"
toys.save
else
Category.create(:name => "More Toys")
end
Run rake db:seeds and that code will run. You just need to consistently update the seeds.rb file every time you change your data, so that 1) it's searching for the right data value and 2) it's updating the correct attributes.
In the end there's no right or wrong way to do this, it's just whatever works for you and your workflow.
The place to load development data is db/seeds.rb. Since you can write arbitrary Ruby code there, you can even load your dev data from external files, for instance.
there is a file called db/seeds.rb
you can instantiate records using it
user1=User.create(:email=>"user#test.com",
:first_name=>"user",
:last_name=>"name",
:bio=>"User bio...",
:website=>"http://www.website.com",
:occupation=>"WebDeveloper",
:password=>"changeme",
:password_confirmation=>"changeme",
:avatar => File.open(File.join(Rails.root, '/app/assets/images/profiles/image.png'))
)
user2=User.create(:email=>"user2#test.com",
:first_name=>"user2",
:last_name=>"name2",
:bio=>"User2 bio...",
:website=>"http://www.website.com",
:occupation=>"WebDeveloper",
:password=>"changeme",
:password_confirmation=>"changeme",
:avatar => File.open(File.join(Rails.root, '/app/assets/images/profiles/image.png'))
)
Just run rake db:seed from command line to get it into the db

NHibernate composite application - startup records for module

I am building a composite (Prism) WPF application. I hava managed to build some core elemets: for example module discovery from folder.
I am also using NHibernate (Fluent) to persist data. I was able to separate modules so every has it's own model and mapping, and when Prism adds module it also adds mappings to my nh configuration.
What I would like to do is to insert some startup records when a module, that has never been started, is enabled.
For example:
When I first start my app, it detects that there is no db and creates one, only with one configuration table. This table contains info about which module is enabled. Then admin can configure app through UI which modules should be enabled. Next time the app starts it detects new tabs from newly enabled modules and creates their tables using NH UpdateSchema. What I would like to do is to also insert some startup records with this table create.
I think this should be done by NH events (NH documentation on events). Something like 'PostTableCreateEvent' would be nice but I can't find anything like this.
Did any of you do something like this?
Events are triggered in sessions but Schemaexport doest take sessionfactories or sessions, so you cant hook in there. For this what you want there is <database-object><create>INSERT ...</create><drop></drop></database-object> in xml mappings or plain sql since FNH doesnt support <database-object> afaik.
Option 1: add fluent and hbm.xml mappings on creation of NH-Configuration and embed Mappings with <database-object>
Option 2: allow Modules to take additional steps (sql) after Creation of tables ( for one of my projects i wrapped Schemaexport in my own class/Method which also creates the database itself which isnt handled by schemaexport and inserts custom data like schemaversion and configs)