Unable to apply code first migrations to mysql database - mysql

I am working on asp.net mvc with EF code first model. I am trying to apply migrations using EF code first to my project. I am using MySql database. currently i am using EF 4.3.1 version and mysql connector/.net of 6.6.4.0 version. I am successfully add migrations to my project that means i execute series of commands that gave no errors for me. I have followed these steps,
PM> Enable-Migrations
PM> Add-Migration InitialMigration
PM> update-database -verbose
these steps create Migration folder to my project and inside Migration folder it creates configuration and timestamp_Initialmigration files, in configuration file i have added following code.
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
after that i have added one field to my class like,
public int newprop{get; set;}
after that i execute update-database -verbose command in PM console.
when i execute my application it throws an error like,
"Unknown column 'Extent1.newprop' in 'field list'"
please guide me why i am getting this error does i went to the wrong way please guide me.

If your not using automatic migrations
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
public class MyMigrationConfiguration : DbMigrationsConfiguration<MyDbContext>
{
public MyMigrationConfiguration()
{
AutomaticMigrationsEnabled = true; // Are you using this ?????
AutomaticMigrationDataLossAllowed = true;
}
}
Then you need to tell EF using the PM Commandlet to add another migration and update the database.
PM> Enable-Migrations //already done this ?
PM> Add-Migration myLabel
PM> Update-Database
Search for "code based migrations" on web for help

This is a bit late to answer OP... But since it pops up as my first hit on google, ill go ahead anyways :)
The problem here is, that there are a number of restrictions on MySQL as compared to MSSQL.
* In particular with mysql on casesensitive filesystems (linux hosts), table names may not include capitalized letters.
* Also keys are restricted to 767 bytes and should/must be integer types.
* Then there is a problem in parts of the migration generators from Mysql.Data package. For instance when renaming, 'dbo' is not stripped away.
Have a look at this guide on insidemysql.com. It describes how to reconfigure the Aspnet.Identity stack for using int in the TKey typecast.
I have a project where i also have hooked into HistoryContext, allowing to alter structure of __MigrationHistory. It renames and resizes the table/columns. There's also the remake of IdentityConfig - so have a look at
https://github.com/mschr/ASP.NET-MVC5.MySql-Extended-Bootstrap/tree/master/my.ns.entities/DbContexts/MigrationConfig
https://github.com/mschr/ASP.NET-MVC5.MySql-Extended-Bootstrap/tree/master/my.ns.entities/IdentityConfig
Then hook it up with your context (see IdentityDbContext) and enable the mentioned MySqlMigrationScriptGenerator and HistoryContextFactory in your Migrations.Configuration class (see my IdentitiyMigrations.Configuration)

Related

ASP.NET Web Application and MySQL with custom Identity Storage

I want to implement a new WebApp in an existing MySQL database, the problem appears when I try to do the migration or the connection because I have already an 'Users' table in there, so I want to create my own tables (webapp_users, webapp_roles, ...).
I tried several ways to do it but no one worked, Can you help me and tell me the steps to follow to do this from the 'New > Project...' step?
Should I install the MySQL packages from the NuGet Package Manager, use external tools/addons, ...?
I will appreciate that, I'm completely blocked.
Create a db in your MySql server with the required tables and follow these steps :
Import MySql.Web, MySql.Data and MySql.Data.Entity.EF6 dlls into your project first.
Now create a Entity framework data model from your database by right clicking any folder -> new item -> Data -> ADO.net entity data
model
Click Generate from database -> Next
Click on New Connection -> Change ->
Select MySql Database as datasource
Give your MySql server credentials and select database to generate the data model from database
It should work fine.
Edit :
You can also pass the name of the connection string (stored in the web.config) in your context to the base constructor of the IdentityDbContext
public class MyDbContext : IdentityDbContext<MyUser>
{
public MyDbContext()
: base("TheNameOfTheConnectionString")
{
}
}
Check this for more info

Symfony3 : Generate crud doesn't work

I'm trying to use the generate crud feature with my new symfony3 project. I have created a bundle named AdminBundle with the generator, the entity test, also with the generator, all processed well to the end. I checked my file under, i have my class Test.php generated under my src/AdminBundle/Entity/Test.php folder. All is working well.
But when i try to generate a crud following the doc for my test entity with the following command :
bin/console generate:doctrine:crud
The Entity shortcut name: AdminBundle:Test
I get the following error :
[RuntimeException]
Entity "Test" does not exist in the "AdminBundle" bundle. You may have mistyped the bundle name or maybe the entity doesn't exist yet (create it first with the "doctrine:generate:entity" comm
and).
As i said, i already generated the entity with the "doctrine:generate:entity" command, and i type the same name ( AdminBundle:Test ) as i type in my crud generator.
Any ideas ?
I have the same problem with sf2.8.
What I did to solve this problem was:
first: generate the form for the entity.
php app/console doctrine:generate:form NameBundle:EntityName
Second: generate the CRUD for Entity
php app/console doctrine:generate:crud
I just ran into this problem. One of my entity's attributes annotations were mistyped, causing this error. Check your attributes annotations.
I had to do bin/console doctrine:schema:update for it to acknowledge the entity as I had the class but the entity was not in the DB yet.
It's an old issue. But I face it too, just now. I solved it by pointing the class with whole name space.
$test = new \AppBundle\Entity\Test();

Grails package change for domain class caused DuplicateMappingException

While working through a tutorial to start learning Grails, I made a mistake and ran:
grails create-domain-class com.FooBar
instead of:
grails create-domain-class com.acme.FooBar
It was immediately obvious I had made an error so I tried the following:
Searched for a function that reverses the create-domain-class command, it seems there isn't one.
Searched for advice on the web and the consensus is that you can delete a domain class file, any associated views and tests, then to be safe run a text search for your class name in your project directory for any references you may have missed. I have done all this.
Then I ran the correct command to create com.acme.FooBar, which worked.
After this the app fails to run and reports the following error:
org.hibernate.DuplicateMappingException: duplicate import: FooBar refers to both com.acme.FooBar and com.FooBar (try using auto-import="false")
After adding the following code to com.acme.FooBar:
...
static mapping = {
autoImport false
}
...
The app now runs as expected.
However as an experienced Java developer who occasionally does refactor a package I would like to understand how to do that without causing a DuplicateMappingException or resorting to the "autoImport false" solution.
Thanks.
You shouldn't be doing
static mapping = {
autoImport false
}
As, by doing this you said that don't check for domain just by name and look up for package as well. Hence, once you do that you will have to use Fully qualified name of the class in your queries / hqls which may itch sometimes.
You should be removing the Domain completely i.e.
remove the Domain
remove the view folder creating by default with very same name and so do the controller
Now, do grails clean-all(Make it a thumb rule to use grails clean-all first for any issue unexpectedly occuring).
To be more accurate do remove target directory from your project and then do run grails run-app.
I had done very same thing many times and got it resolved by above steps.
Hope it helps.

Change Entity Framework database schema map after using code first

I've finished building my blog using EF and Code First.
EF was running against my local SQL Express instance, with [DBO] schema.
Now i want to publish the blog, and i have done the following :
Generetade the scripts for the tables and all objects from SQL Express and change [dbo] to my [administrator] schema from my server.
Ran the scripts against the server. No issues, all objects were created an populated just fine.
I have modified Webconfig and added my BlogContext connection string to point to the server not local sql express.
Published the site.
The error i am getting is : Invalid object name 'dbo.Articles'. - where Articles is one of my entities. It resides on my sql server, [Administrator].Articles.
As far as i can tell EF still thinks im using the DBO schema. Although i have added the connection string to point to administrator user.
How can i change the schema that EF thinks it should use?
EF will use dbo schema if you didn't configure the schema explicitly through data annotations or fluent API.
[Table("MyTable", "MySchema")]
public class MyEntity
{
}
Or
modelBuidler.Entity<MyEntity>().ToTable("MyTable", "MySchema");
Just for searchers: I am just working with EF5 .NET4.5, and
[Table("MyTable", "MySchema")]
does not work. Even if VS2012 shows there is an overload which takes 2 parameters, on build it gives the error: 'System.ComponentModel.DataAnnotations.Schema.TableAttribute' does not contain a constructor that takes 2 arguments.
But the code mapping works just fine.

Entity Framework 4 Code First - Prevent DB Drop/Create

I've written an ASP.Net MVC 3 application using the Code First paradigm whereby when I make a change to the model the Entity Framework automatically attempts to re-create the underlying SQL Server Database via DROP and CREATE statements. The problem is the application is hosted on a 3rd party remote server which limits the number of databases I can have and does not seem to allow me to programmatically execute "CREATE DATABASE..." statements as I gather from this error message:
CREATE DATABASE permission denied in database 'master'.
Is there any way to stop the Entity Framework from dropping and attempting to re-create the whole database and instead make it simply drop the tables and re-create them?
After creating the database manually and running the application I also get the following error I guess as the Entity Framework tries to modify the database:
Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.
UPDATE: Found this gem through google, it sounds like its exactly what you need: http://nuget.org/Tags/IDatabaseInitializer
You can use a different database initializer. Lets say your context is called SampleContext then your constructor would look like this:
public SampleContext()
{
System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<SampleContext>());
}
Note that the above is the default initializer. You will probably need to create your own custom initializer by implementing IDatabaseInitializer. Theres some good info here: http://sankarsan.wordpress.com/2010/10/14/entity-framework-ctp-4-0-database-initialization/
Using EF 4.3 with Migrations you do not get this behavior - at least I have not seen it. But I also have this set in my code -
public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
public DbConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}