MySql EF Code First migrations VB.NET - mysql

I have been playing around with Entity Framework and MySql using the Code First approach,
When I run my code against a newly created MySql Server with no databases etc (apart from the defaults) It creates the database and tables according to the classes I have created. My issue is and I don't know if I'm doing this right is, if I make a change to my model class for example add a new property I would expect a new column to be added to that particular table. However this isn't the case instead I'm getting an error
Unknown column: 'Extent1.Email' in 'field list'
I know this is because I have made a change to the class, but I am under the impression that EF would be able to make that change automatically to the database.
I have Installed
EF 6.1.1
MySql.Data 6.9.3
MySql.Data.Entity 6.9.3

All your db initialization takes place in
Interface IDatabaseInitializer(Of In TContext As System.Data.Entity.DbContext)
You can set it in your DbContexts constructor using Entity.Database.SetInitializer() or configure it in your Web.config in <entityFramework><contexts><context><databaseInititalizer>.
To get your new columns in your existing database, you need to either do the necessary migrations (see http://msdn.microsoft.com/en-us/data/JJ591621.aspx) or you drop and recreate the database on every model change (which is what the DropCreateDatabaseIfModelChanges implementation of IDatabaseInitializer does, see http://www.adfa.se/Archive/2013/02/01/database-initializers-in-ef-code-first).
Without further information I recommend you to do the latter.

Related

mySQL Auto increment using JDBC

I have created a page and want to store it in mySQl but i want to implement autoincrement from my java program and pass it as a parameter.how to get that.I used static count=0 counter as passing but it is not happening.
This is the function i am using
static int=count++;
CorruptionStory corruptionStory =
new CorruptionStory(count, new State(stateId,stateNameSelected),
age, new Department(deptId,departmentNameSelected),
positionOfOfficial,bribeAmount, description, sqlDate);
isSuccessfullySaved = CorruptionStoryJdbcImpl.
saveCorruptionStory(corruptionStory);
I don't think it's a good idea to have the java code manage the auto incrementing of the number, you should really configure your table schema to do it for you. Here is why:
if you restart your application, you will need to write code to figure out what number to resume with.
if you have multiple instances of your program running, they will somehow need to coordinate with each other so they don't use the same number.
MySQL column definitions allow you to specify auto-increment, see this:
http://dev.mysql.com/doc/refman/5.6/en/example-auto-increment.html
it would be much better if you wrote a SQL schema file to solve this problem. Then, when you do the insert statement from the java program, you can omit that column, and MySQL will automatically set it to the next appropriate value.
Also, if you are willing to spend time studying hibernate, you can use that. Hibernate is able to generate your SQL schema automatically for you, and even update the database for you at startup. It has an annotation that lets you tell hibernate that a certain class field (table column) should be an automatically incrementing id.
I should warn you though, hibernate is not something you're going to learn overnight.

Adding Model Attribute with MySQL later in project

I have a working django project and I want to add a new model attribute. How do I do this?
Currently I have done
class Stream(models.Model):
workingattributes = models.CharField(max_length=100)
step = models.CharField(max_length=1)
when I run 'python manage.py runserver' I receive a
DatabaseError: (1054, "Unknown column 'livestream_stream.step' in 'field list'")
I have gone into MAMP and accessed my database and added a new column 'step', but I receive the same error. Anyone have recommendations on how to add new attributes? THanks
You need to use South (or something similar) to do a Schemamigration. Read the documents to see how to do it. It's quite easy, and will be very helpful later in your project (when you have lots of data in your database). The only other option (other than using another migration tool) is to drop the database and create it again, which would lose you all of your data.
You should use South as per #Daniel Rosenthal suggestion, but the reason you are still receiving an error after creating the column is that the column you create should be named appname_modelname not just model_name so you need foo_step

Linq to SQL: Removal of column from DB and code causes invalid column error

I have a very very simple implementation of linq to sql in a sharepoint 2010 service application, but ran into a bit of a roadblock.
There are no generated classes, im just using a System.Data.Linq.Mapping statement, a [Table(Name="")] tag in the class and the columns with a [Column(Name="")] tag. And in the context object I made, it extends the DataContext class, and has a Table<> object. Nothing more.
Yesterday I was asked to remove a column from the DB (fairly late in implementation) but it was a simple job. I deleted the column from the db, removed the object from the class and went through all of my affected code to remove references to this old column.
However, I am getting an Invalid Column Error whenever the linq to sql object for that table is used.
I have deleted the table and recreated it, cleaned my VS solution, rebuilt it, re checked it out from our repo, deleted all generated objects from the file system and have yet to fix this.
Does anyone have an idea of how to fix it?

Grails Change ID type on existing database

I have an existing application in grails using mysql database with much data. The previous programmer uses int as id and I need to change to long as I'm running out of ids. I know that the change in the domain class does not update the column of the existing table. Do I change the type in mysql manually?
There's this thing called database migrations... There's a plugin for it.
http://grails.org/plugin/database-migration
Yes, after changing the domain class change the column manually.
Also, I suppose it's a good idea first to set dbUpdate to e.g. "create-drop" and try it (on another DB instance) to let Grails generate new schema and to see whether it looks as you expect.
So, change the domain, generate test schema and check whether it is correct, then change the original DB manually.

Entity Framework 4.1 Custom Database Initializer strategy

I would like to implement a custom database initialization strategy so that I can:
generate the database if not exists
if model change create only new tables
if model change create only new fields without dropping the table and losing the data.
Thanks in advance
You need to implement IDatabaseInitializer interface.
Eg
public class MyInitializer : IDatabaseInitializer<MyDbContext>
{
public void InitializeDatabase(MyDbContext context)
{
//your logic here
}
}
And then set your initializer at your application startup
Database.SetInitializer<ProductCatalog>(new MyInitializer());
Here's an example
You will have to manually execute commands to alter the database.
context.ObjectContext.ExecuteStoreCommand("ALTER TABLE dbo.MyTable ADD NewColumn VARCHAR(20) NULL");
You can use a tool like SQL Compare to script changes.
There is a reason why this doesn't exist yet. It is very complex and moreover IDatabaseInitializer interface is not very prepared for such that (there is no way to make such initialization database agnostic). Your question is "too broad" to be answered to your satisfaction. With your reaction to #Eranga's correct answer you simply expect that somebody will tell you step by step how to do that but we will not - that would mean we will write the initializer for you.
What you need to do what you want?
You must have very good knowledge of SQL Server. You must know how does SQL server store information about database, tables, columns and relations = you must understand sys views and you must know how to query them to get data about current database structure.
You must have very good knowledge of EF. You must know how does EF store mapping information. You must be able to explore metadata get information about expected tables, columns and relations.
Once you have old database description and new database description you must be able to write a code which will correctly explore changes and create SQL DDL commands for changing your database. Even this look like the simplest part of the whole process this is actually the hardest one because there are many other internal rules in SQL server which cannot be violated by your commands. Sometimes you really need to drop table to make your changes and if you don't want to lose data you must first push them to temporary table and after recreating table you must push them back. Sometimes you are doing changes in constraints which can require temporarily turning constrains off, etc. There is good reason why tools which do this on SQL level (comparing two databases) are probably all commercial.
Even ADO.NET team doesn't implemented this and they will not implement it in the future. Instead they are working on something called migrations.
Edit:
That is true that ObjectContext can return you script for database creation - that is exactly what default initializers are using. But how it could help you? Are you going to parse that script to see what changed? Are you going to execute that script in another connection to use the same code as for current database to see its structure?
Yes you can create a new database, move data from the old database to a new one, delete the old one and rename a new one but that is the most stupid solution you can ever imagine and no database administrator will ever allow that. Even this solution still requires analysis of changes to create correct data transfer scripts.
Automatic upgrade is a wrong way. You should always prepare upgrade script manually with help of some tools, test it and after that execute it manually or as part of some installation script / package. You must also backup your database before you are going to do any changes.
The best way to achieve this is probably with migrations:
http://nuget.org/List/Packages/EntityFramework.SqlMigrations
Good blog posts here and here.