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
Related
I am creating an MVC application with MySQL as backend. I am planning to use Entity Framework to work with this database. I already have a database so need to generate models from a database
Environment:
MySQL Server 5.7.21
MySQL for Visual Studio 1.27
Connector/NET 6.10.5
Visual Studio 2015
To Reproduce Issue:
Step 1: Add new item 'Ado.net Entity Data Model'
Step 2: Selected 'EF Designer from database' and click 'Next'
Step 3: Clicked 'New Connection'
There is no mysql connector available.
Other Details:
I already added "System. Runtime" deal as it shows error when installing Mysql. data. Ef6 from nugget
I changed "CopyLocal= true" in 'System. Data' assembly reference
I tried the same steps in Visual Studio 2017. Here I can see the provider in the step 3 but after click ok dialogue closed instead of showing table list
In Visual Studio 2015 and 17 initial time it shows the provider. when I tried next time it's not displaying
Please help. I am checking this for 2 days
To start working with VS 2013 and EF 6
Install the MySQL for Visual Studio 1.1.1
Install the Connector/Net 6.8.1 product.
To work with Database first please do the following
Add the reference for the new assembly called MySql.Data.Entity.EF6 and copy it to the bin forlder of your application.
Add the provider to your app/web config file on the providers for Entity Framework section with the following line:
Before you run the Wizard compile your application so the new changes are applied.
To work with Model First please do the following
Add the reference for the new assembly called MySql.Data.Entity.EF6 and copy it to the bin forlder of your application.
Add the ADO.Net Entity Model new or existing.
Select the T4 template corresponding to MySQL (SSDLToMySQL)
Right click on the model and then select Generate Script to Create Database. (A MySQL script should be generated for you to create your database).
Hope this helps a bit.
MySQL for Visual Studio 1.1.1
MySQL Connector/Net 6.8.1 Beta
As MaDOS mentioned, mySql is not realy supported. If you want to use EF anyway you have to do a code-first-attempt.
You have to write the mapping-classes, and tell EF that it should NOT change the db.
Example context with disabled db-changes
public class MySqlDbContext : DbContext
{
public DbSet<MyOrderClass> Orders { get; set; }
public MySqlDbContext(IDbConnection connection)
: base((DbConnection)connection, false)
{
Database.SetInitializer<MySqlDbContext>(null); // Disable db-changes by dbContext
}
}
You main Problem are the data-types. Outside the MS-world not all data-types are supported (Oracle also got some problems with DateTime). In example-class below the "Created"-column is handled as string, which always works. In your .Net-application, you have to implement "converter"-properties which map to the desired type.
Example-Class with mapping-configuration
[Table("TORDERS")]
public class MyOrderClass
{
[Column("ORDERID")]
public long Id { get; set; }
[Column("CREATED")]
public string CreatedString { get; set; }
[NotMapped]
public DateTime? Created
{
get
{
DateTime tmp;
if (DateTime.TryParse(this.CreatedString, out tmp))
return tmp;
return null;
}
set
{
this.CreatedString = value.HasValue ? value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null;
}
}
}
static void Main(params string[] args)
{
MyOrderClass tmp = new MyOrderClass() { CreatedString = "2018-01-01 11:11:11"};
Console.WriteLine(tmp.Created.ToString()); // This is how you want to work
tmp.Created = null;
Console.WriteLine(tmp.CreatedString); // this is surely not what you want to do
tmp.Created = new DateTime(2018,02,02,10,10,10);
Console.WriteLine(tmp.CreatedString); // Check if setter works ;)
}
Im not uptodate which types work, but with this you'll always be able to use EF.
We used it some time ago to access an existing db, which hat an awful db-schema anyway, because of the schema we hat to setup the datatypes anyway ;).
Could it be a 32bit vs 64bit problem?
Example: 64bit driver installed Visual studio is 32bit?
I have that problem all the time with oledb to Informix. your sofware will work perfectly in 64bit, but the tooling is 32bit.
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)
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.
We're running into a small problem deploying a web application to another environment.
We created the application's db using Entity Framework Code First approach (db automatic created from Model).
In this development environment, we are using integrated security and the tables are created under the dbo user. The tables are like
[dbo].[myTable]
For our other environment, we are using username/password authentication for the DB.
We scripted the tables and created them on the DB. So they are now named like
[myDbUser].[myTable]
When running the application, we encounter always the problem
Invalid object name 'dbo.myTable'.
Seems like the code is still trying to look for a dbo table, which is not present and thus fails.
Can anyone shed some light on this problem? Where does Entity Framework gets this dbo prefix from?
Thanks
Specify schema explicitly:
[Table("Users", Schema = "dbo")]
public class User { .. }
Or specify default db schema for your user - 'dbo'
To specify schema in fluent
protected override void OnModelCreating(DbModelBuilder modelBuilder)
modelBuilder.Entity<ClassName>().ToTable("TableName", "SchemaName");
I ran into this issue recently as well as we support several different schemas with the same model. What I basically came up with was the passing the schema name to the classes/methods that map the model. So for example, EntityTypeConfiguration subclasses take the schema name as a constructor argument, and pass it along with the hard-coded string to ToTable().
See here for a more detailed explanation: https://stackoverflow.com/a/14782001/243607
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;
}
}