Fail to run Code-First Migration - RenameColumn - with MySql - mysql

I have an issue which I could not find answer for across the web.
I am using CodeFirst EF 4.3.1 Migrations with MySQL.
My MySQL provider is Devart.
After running Add-Migration against an existing database, I got the following code:
public partial class ChangeSet_1231 : DbMigration
{
public override void Up()
{
RenameColumn(table: "RW_TTaskInstanceProperties", name: "TaskInstance_TaskInstanceId", newName: "TaskInstanceId");
}
public override void Down()
{
RenameColumn(table: "RW_TTaskInstanceProperties", name: "TaskInstanceId", newName: "TaskInstance_TaskInstanceId");
}
}
Running Update-Database results in the following error:
PM> Update-Database -verbose –startupprojectname "RTDataAccess"
Using NuGet project 'RTDataAccess'.
Target database is: 'rsruntime' (DataSource: localhost, Provider: Devart.Data.MySql, Origin: Explicit).
Applying explicit migrations: [201205311312361_ChangeSet_1231].
Applying explicit migration: 201205311312361_ChangeSet_1231.
ALTER TABLE RW_TTaskInstanceProperties RENAME COLUMN TaskInstance_TaskInstanceId TO TaskInstanceId
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'COLUMN TaskInstance_TaskInstanceId TO TaskInstanceId' at line 2
From looking at the error details I see that the RenameColumn is translated to a MsSql command, rather than MySql command, so no wonder it reports about a syntax error.
Any ideas how to solve it?
I know I can use Update-Database -script, then edit the script to fit MySql and run it, but I prefer to make the Update-Database command work...
Thanks.
In response to Ladislav's question:
Yes, I registered the Devart's SQL generator for MySQL Migrations.
My Configuration class looks like that:
using Devart.Data.MySql.Entity.Configuration;
using Devart.Data.MySql.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<RTDataAccess.RTContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MySqlEntityProviderConfig.Instance.Workarounds.IgnoreSchemaName = true;
var connectionInfo = MySqlConnectionInfo.CreateConnection("Server=xxxx;Port=yyyy;Database=rsruntime;Uid=zzzz;Pwd=wwww;charset=utf8;");
this.TargetDatabase = connectionInfo;
this.SetSqlGenerator(connectionInfo.GetInvariantName(), new MySqlEntityMigrationSqlGenerator());
}
protected override void Seed(RTDataAccess.RTContext context)
{
}
}

The issue was fixed by Devart.
Details at the following links:
http://forums.devart.com/viewtopic.php?f=2&t=24250
http://www.devart.com/dotconnect/mysql/download.html

Related

A network-related or instance-specific error occurred while establishing a connection to SQL Server. Code-first ef core 6

I am building my first application using .Net 6 EF Core.
I want to use the code-first method.
When I try to migrate using Update-Database (after I get this error:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I have a "local instance of MySQL80" running on my machine. I can connect to it, using a DB tool, like Dbeaver or the MySQL Workbench.
This is the Connection String I am using:
"ConnectionStrings": {
"DevConnection": "Server=localhost;Database=my-desired-db-name;Trusted_Connection=True;"
}
This is my Program.cs:
using Microsoft.EntityFrameworkCore;
using react_chores_prototype_api.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<MyDBContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DevConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
I know that this question came up a few times already, but I cant find a solution with the given explantations, also because of lots of different versions over the years. If someone can maybe help me, so i can start working on my project, that would be greatly appreciated.
EDIT:
I installed Pomelo MySql Provider and changed the connectionString to a mysql one.
Also i changed my Program.cs like this:
var conString = "Server=localhost;Database=my-db-name;Uid=root;Pwd=verySecurePw;";
builder.Services.AddDbContext<MyDBContext>(options => options.UseMySql(connectionString: conString, ServerVersion.AutoDetect(conString)));
Now it seems to work, I just get following SQL Syntax Error (Not really related to the original Question I guess):
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'NOT NULL,
Description nvarchar(200 NOT NULL,
Points int NOT NULL,
Related to this Model:
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace react_chores_prototype_api.Models
{
public class Task
{
[Key]
public int Id { get; set; }
[Column(TypeName = "nvarchar(50)"]
public string Name { get; set; }
[Column(TypeName = "nvarchar(200)"]
public string Description { get; set; }
public int Points { get; set; }
}
}

entity framework mysql connection string error?

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseMySql(#"server=localhost;port=3306;database=shopDb;user=root;password=mysql123;");
}
I am trying to connect entity framework and mySQL. Why i get this error? (Cannot convert 2 arguments from 'string' to 'MicrosofEntityFrameworkCore.ServerVersion')
code
You have an error in your connection string. Try to remove a port since you are using a local host.

Microsoft.EntityFrameworkCore 2.1-rc with MySql.Data.EntityFrameworkCore

I'm trying to use mysql with Microsoft.EntityFrameworkCore 2.1-rc-final and MySql.Data.EntityFrameworkCore 8.0.11 as provider. But when I'm trying to execute the mugrations command i get this exception:
System.MissingMethodException: Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilderFactory..ctor(Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1, Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'.
This is my IDesignTimeDbContextFactory code implementation:
public class DesignLocationFactory:IDesignTimeDbContextFactory<LocationDbContext>
{
public LocationDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<LocationDbContext>();
builder.UseMySQL("server=localhost;port=3306;user=***;passsword=***;database=locationdb");
return new LocationDbContext(builder.Options);
}
}
Please how can I fix this or at least some sample of how to use with another providers
Finally, with this provider Pomelo.EntityFrameworkCore.MySql version 2.1.0-rc1-final everything works perfect.
To install it execute the command:
Install-Package Pomelo.EntityFrameworkCore.MySql -Version 2.1.0-rc1-final
I can confirm that 2.1.0-rc1-final resolves this issue. Also, take note of Pomelo's case sensitivity vs Microsoft.EntityFrameworkCore.
Pomelo = UseMySql (Sql)
EntityFrameworkCore = UseMySQL (SQL)
Using Core 2.1
Id Versions
-- --------
Microsoft.AspNetCore.App {2.1.0}
Microsoft.VisualStudio.Web.CodeGeneration.Design {2.1.0}
Microsoft.EntityFrameworkCore.Tools {2.1.0}
Microsoft.NETCore.App {2.1.0}
MySql.Data.EntityFrameworkCore.Design {8.0.11}
MySql.Data.EntityFrameworkCore {8.0.11}
Pomelo.EntityFrameworkCore.MySql {2.1.0-rc1-final}

Problems migrating ASP.NET Core Identity from SQL Server to MySQL

I am working on migrating my ASP.NET Core project from using Microsoft SQL Server to MySQL now that the MySQL DB provider has been released("pre-released"). I was using Core Identity for membership when using SQL Server and it worked in that configuration. When I migrated the DB to MySQL (using the migration wizard in MySQL Workbench), I began receiving this error when saving a new user to the DB:
No mapping to a relational type can be found for the CLR type 'Microsoft.EntityFrameworkCore.Metadata.Internal.Property'
The error comes in this code when executing the CreateAsync method:
public IActionResult Register([FromBody]RegisterViewModel obj)
{
if (ModelState.IsValid)
{
IdentityUser user = new IdentityUser();
user.UserName = obj.Username;
user.Email = obj.Email;
IdentityResult result = _userManager.CreateAsync(user, obj.Password).Result;
}
}
Here is my DbContext class:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace PilotMaltApiCore.Models
{
public class PilotDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
public PilotDbContext(DbContextOptions<PilotDbContext> options)
: base(options)
{
//nothing here
}
public DbSet<Batch> Batches { get; set; }
public DbSet<Bag> Bags { get; set; }
public DbSet<Vendor> Vendors { get; set; }
public DbSet<Variety> Varieties { get; set; }
}
}
I was thinking it may have something to do with the difference in datatypes between SQL Server and MySQL. Here is the SQL Server table:
And here is the MySQL table after using the migration wizard in MySQL Workbench:
Keep in mind, all of the code worked fine when using SQL Server. Your help is appreciated, thanks!
This tutorial worked well for me:
http://blog.developers.ba/asp-net-identity-2-1-for-mysql/
I changed the charset for the varchar fields to utf8mb4 which fixed the issue.
I also chose to use Sapient Guardian's version of the MySql provider for .net Core and which has proved much less problematic than MySql's version. It can be downloaded here.

Create database play java evolutions

I am using play java 2.5.
I have created a database with following java code.
public OnStartup() throws SQLException {
//demo create database with java code
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=12345678");
Statement s = con.createStatement();
int Result = s.executeUpdate("CREATE DATABASE recruit3");
}
Module:
public class OnStartupModule extends AbstractModule {
#Override
public void configure() {
bind(OnStartup.class).asEagerSingleton();
}
}
application.conf:
play.modules {
enabled += "be.objectify.deadbolt.java.DeadboltModule"
enabled += modules.CustomDeadboltHook
enabled += modules.OnStartupModule
}
default.driver=com.mysql.jdbc.Driver
default.url="jdbc:mysql://localhost:3306/recruit3"
default.username=root
default.password="12345678"
My question is, why running the web-app creating
error Cannot connect to database [default]
How to fix that, if I don't want to create the database with mysql workbench.
Any suggestion or cannot do this, please tell me.
Thanks for advance.
As well as moving your database keys to the db.default namespace, you should be injecting Database into OnStartup to access the database configured with those properties.
First, add Play's JDBC support to build.sbt.
libraryDependencies += javaJdbc
If you're already running activator, make sure you use the reload command to pick up the changes to the build.
Update your application.conf to place the database configuration into the correct namespace.
db {
default {
driver=com.mysql.jdbc.Driver
url="jdbc:mysql://localhost:3306/recruit3"
username=root
password="12345678"
}
}
Finally, update OnStartup to receive a Database object that will be injected by Play.
import javax.inject.Inject;
import play.db.Database;
public class OnStartup {
#Inject
public OnStartup(final Database db) throws SQLException {
db.withConnection((Connection conn) -> {
final Statement s = con.createStatement();
return s.executeUpdate("CREATE DATABASE recruit3");
});
}
}
This allows you to configure the database one time, in application.conf, instead of hard-coding DB configuration into a class.
You can find more information here.
Your database keys start with default instead of db.default. The correct syntax is something like this:
db {
default {
driver=com.mysql.jdbc.Driver
url="jdbc:mysql://localhost:3306/recruit3"
username=root
password="12345678"
}
}
You already made your class as eager singleton, so it should work