Scaffolding a MySQL view using Pomelo and .Net Core 2.1 - mysql

Apparently, with .Net Core 2.1, views are now supported. I was wondering if it is possible to scaffold a view using Pomelo, and if so, what the syntax is? I tried the "table" syntax with a view but it didnt work:
dotnet ef dbcontext scaffold "Server=myserver.com;Database=myDatabase;User=userame;Password=password;" "Pomelo.EntityFrameworkCore.MySql" -t personsView -o models
It runs, but it only generates a dbContext - it doesn't generate the model.
I'm using Pomelo 2.1.1 and Visual Studio 2017 (15.7.5). My project is a .Net Core 2.1 Web API. On the back end, I have MySQL Server 5.6.30.

Using Pomelo, you can use the following command (within the Package Manager Console) to generate the models as well as the context class:
Scaffold-DbContext [CONNECTION_STRING] Pomelo.EntityFrameworkCore.MySql -OutputDir [OUTPUT DIRECTORY] -Context [NAME OF CONTEXT CLASS] -f

Related

Unable to resolve service for type Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger

I am having difficulties to scaffold an existing MySQL database using EF core.
I have added the required dependencies as mentioned in the oracle doc:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkcore.Tools" Version="6.0.0">
and then, I ran this code in the package manager console:
Scaffold-Dbcontext "server=the.server.ip.address;user=user_name;database=db_name;password=db_password;port=3306" MySql.EntityFrameworkCore -o Data -v
It shows this error:
Unable to resolve service for type
'Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1[Microsoft.EntityFrameworkCore.DbLoggerCategory+Scaffolding]'
while attempting to activate
'MySql.EntityFrameworkCore.Scaffolding.Internal.MySQLDatabaseModelFactory'
Here are the relevant logs in the output window:
Finding design-time services referenced by assembly 'Test2'...
Finding design-time services referenced by assembly 'Test2'...
No referenced design-time services were found.
Finding design-time services for provider 'MySql.EntityFrameworkCore'...
Using design-time services from provider 'MySql.EntityFrameworkCore'.
Finding IDesignTimeServices implementations in assembly 'Test2'...
No design-time services were found.
I don't know how shall I implement the design time classes and nor did I find any useful links in the web.
Note that I can access and run query on the database using MySQL Workbench.
I got this error not while scaffolding but when trying to create my first migration. I didn't want to downgrade to 5.0 because it would've had to be permanent since I was going to run a lot of migrations.
I fixed it by changing my provider from MySql.Data.EntityFrameworkCore to Pomelo.EntityFrameworkCore.MySql
Remove the old provider from both my API and DAL projects:
dotnet remove package MySql.EntityFrameworkCore
Add Pomelo provider
dotnet add package Pomelo.EntityFrameworkCore.MySql
Update your startup to use Pomelos configuartion:
https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql#2-services-configuration
Migrations are working:
dotnet ef migrations add InitialCreate
According this description
https://bugs.mysql.com/bug.php?id=106592
you can solve this error by adding below class to your code
public class MysqlEntityFrameworkDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddEntityFrameworkMySQL();
new EntityFrameworkRelationalDesignServicesBuilder(serviceCollection)
.TryAddCoreServices();
}
}
and after define you have to add it as service in startup file
like this
services.AddSingleton<IDesignTimeServices, MysqlEntityFrameworkDesignTimeServices>();
After these steps you can migrate your code :)
I came across the same issue trying to scaffold an existing MySQL database. It looks like the latest version of MySql.EntityFrameworkCore (6.0.0-preview3.1) still uses the EFCore 5.0 libraries and has not been updated to EFCore 6.0.
It also seems Microsoft.EntityFrameworkCore.Diagnostics was last implemented in EFCore 5 and removed in 6.
When I downgraded all the packages to the 5 version level, I was able to run the scaffold command without that error.
To make Scaffold-Dbcontext work, I had to downgrade both the packages to 5.0.0 version.
MySql.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
After successful scaffolding, I upgraded these packages back to the their latest versions.
I could find the Core 6.0 documentation for microsoft.entityframeworkcore.diagnostics in the official website, but it was still not working when I tried the Scaffold-DbContext command. Had to downgrade all the packages to the last 5.0 version before it worked. Here are the packagerefs in my project settings
"Microsoft.EntityFrameworkCore.Design" Version="5.0.13"
"Microsoft.EntityFrameworkCore.Tools" Version="5.0.13"
"MySql.Data" Version="8.0.28"
"MySql.EntityFrameworkCore" Version="5.0.10"
#https://stackoverflow.com/users/1322226/quinestor I faced same issue and as #https://stackoverflow.com/users/9914700/james-ruth mentioned I downgraded the versions of all EFCore and EFCore Design to 5.0.8 in Visual Studio.
Did not look around for command line commands :) But we can also do it from from dotnet cli, which I guess you probably would be aware of. We can remove - dotnet remove package <PACKAGE_NAME>, and install specific version - dotnet add package <PACKAGE_NAME> --version
You do not need to perminately downgrade your EF version to scaffold, you can edit the project file to use
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.8" />
</ItemGroup>
Then you can run
dotnet ef dbcontext scaffold "[DSN String]" MySql.EntityFrameworkCore -o [DBName]
Then change your project file back (or revert changes) to use the latest version of EF.
Dont forget to edit the "protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)" and remove the DSN it adds to the code.
The latest version of MySql.EntityFrameworkCore still uses the EFCore 5.0 libraries and has not been updated to EFCore 6.0.
It also appears that Microsoft.EntityFrameworkCore.Diagnostics was removed in 6.
I resolve this error by adding the class below to my code:
public class MysqlEntityFrameworkDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddEntityFrameworkMySQL();
new EntityFrameworkRelationalDesignServicesBuilder(serviceCollection)
.TryAddCoreServices();
}
}
Then you must add it as a service in the initialization file
services.AddSingleton<IDesignTimeServices, MysqlEntityFrameworkDesignTimeServices>();
Hope this helps!

ASP.NET CORE with MySQL and EF Core - Multiple connection string handling

I have ASP.NET CORE 2 application with MySQL 5.7 and EF Core 2.0 in code-first approach.
I have setup my database in replication for Read and Write. So how can I configure my EF Core for these two connection string for respective operations i.e. Read and Write?
It is a good choice to use open source DBMS with .Net core
first of all, install these two packages in your project:
Mysql.Data
Mysql.Data.EntityFrameworkCore
You can do it simply from tools->Nuget packageManager -> package manager console
install-package Mysql.Data
install-package Mysql.Data.EntityFrameworkCore
or install them to your solution(Manage NuGet packages for solution)
After that go to appsettings.json and add the connection string as follow:
{"ConnectionStrings": {
"connectionName":"server=127.0.0.1;port=3306;database=mysqlTestDb;username=mysqlUser;password=mysqlPassword"},
Next, add your Context class and go to your startup.cs class for configuring mysql in DI in the ConfigureServices method add the following code
string connectionString = Configuration.GetConnectionString("mysqlConnectionName");
services.AddDbContext<DbContextName>(Options => Options.UseMySQL(connectionString));
After following all these steps, add migrations and update your database. I hope it works well for you.

Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project

I've been researching a lot online but did not find a proper solution. I was trying to use Entity Framework Core with MySQL by using database-first scaffold method to mapping table model while always received this error when applied the command
Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
This is the command I am using to scaffold the database model:
Scaffold-DbContext "server=localhost;port=3306;user=root;password=1234;database=world" "Pomelo.EntityFrameworkCore.MySql" -OutputDir .\Models -f
And this is my .Net Core project setting:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.1" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
</ItemGroup>
For EF Core 3
I think the powershell command has gone away for EF Core 3 so I'm using dotnet ef dbcontext scaffold
With this command, if you're converting a Scaffold-DbContext script the project name (parameter --project) needs to have .csproj on the end - it can't just the extensionless name.
I got this error trying to add a new migration on the command line with dotnet ef migrations add NewMigration.
The solution for me was indeed to append --msbuildprojectextentionspath obj/local.
For my case this error was solved by downloading latest dotnet-sdk-2.2.107-win-x64
for VS2017 and then dropping and updating database through cmd:
dotnet ef database drop --force --context <<dbcontext>> -s <<startup project directory>> -p <<project directory>>
dotnet ef database update --context <<dbcontext>> -s <<startup project directory>> -p <<project directory>>
Here goes the definitively solution for this problem.
I work with Rider Ide constructing a Web Api, using Net core 3 with Pomelo.MySql
I have tree layers defining my application:
Test.Domain - Class Library defining my models
Test.Infra.DataAccess - Class library defining my DbContext
Test.Service.RestApi - Net Core Api Project, where I define the AppContext in Startup file. Like This:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AerjDbContext>(
options => options.UseMySql(Configuration.GetConnectionString("MySqlConnectionString"),
mysqlOptions => mysqlOptions.ServerVersion(new Version(8,0,19), ServerType.MySql)
.EnableRetryOnFailure()
));
}
This is quite normal, the magic occurs here:
Initiate migrations:
dotnet ef migrations add InitialCreate --startup-project "../<Here the name of the project where startup file was configured>"
It'll create the migrations
then we have to update database with sabe command structure;
dotnet ef database update --startup-project "../<Here the name of the project where startup file was configured>"
I have tried different solutions to solve this error. Did following change in .csproj file.
Solved this issue for .Net Core by edit .csproj file and removed Import tag and then run ef command again in command line.
EF migrations with .NETCore 2.2 can be smoke-tested using migrations list:
dotnet ef migrations list --startup-project <app-startup-project-dir> --project <dal-project-dir> --context App.DAL.ApplicationDbContext
--context must point to the fully qualified name of the DbContext class that you want to manipulate.
Add this parameter to the end of your scaffold command "--msbuildprojectextensionspath".

mySQL Data Provider .NET Core 2.0

Looking for help for some solutions on switching out the default data provider for the project from MS SQL to mySQL. Eventually with the intent of deploying the solution to Auruora on AWS.
After installing the nuget package I get something along the lines of :
System.TypeLoadException: Method 'Clone' in type 'MySql.Data.EntityFrameworkCore.Infraestructure.MySQLOptionsExtension' from assembly 'MySql.Data.EntityFrameworkCore, Version=6.10.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation.
This lead me to believe that there is no .NET 2.0 Entity Framework Core extention that runs for MySQL. Do I have to rollback to a different version?
For EntityFrameworkCore, it's suggested to use Pomelo.EntityFrameworkCore.MySql.
You may refer to their Getting Started documentation.
A fellow member of the community has kindly summarised the essential steps here:
Put Pomelo.EntityFrameworkCore.MySql into the xxx.EntityFrameworkCore project's .csproj file (see step 2 in the Pomelo getting started guide)
In your xxxDbContextConfigurer class put builder.UseMySql(...) rather than builder.UseSqlServer(...)
Change the connection string found in the appsettings.json file in the xxx.Web.Host project

Error while connecting MYSQL with asp.net core

Problem
I am trying to conect MY SQL with my asp.net core 2.0 web application. But it throug me this error
Method 'Clone' in type 'MySql.Data.EntityFrameworkCore.Infraestructure.Internal.MySQLOptionsExtension' from assembly 'MySql.Data.EntityFrameworkCore, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an implementation.
I am using Repository pattern in asp.net core 2.0 with EF 2.0
startup.cs
here the error occurs
services.AddDbContext<MyContext>(options =>
options.UseMySQL(
Configuration.GetConnectionString("DefaultConnection"),
b=>b.MigrationsAssembly("AspNetCoreMultipleProject")
));
It looks like this could be because the official MySQL provider doesn't work with EF core 2.0 - GitHub issue.
The suggested workaround is to use the Pomelo provider - MS documentation