MySql EntityFrameworkCore System.TypeLoadException - mysql

I am trying to connect my web API to MySql database with this code:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
string conn_string = "server=server;database=database;uid=uid;pwd=pwd;";
MySqlConnection conn = new MySqlConnection(conn_string);
services.AddDbContext<TaskContext>(options =>
{
options.UseMySQL(conn);
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
But I always recieve a System.TypeLoadException with this description:
System.TypeLoadException : 'Method 'Clone' in type
'MySQL.Data.EntityFrameworkCore.Infraestructure.Internal.MySQLOptionsExtension'
from assembly 'MySql.Data.EntityFrameworkCore, Version=8.0.8.0,
Culture=neutral, PublicKeyToken=c5687fc88969c44d' does not have an
implementation.'
I am using Microsoft Visual Studio Community 2017 Preview (2) and my projet is in .NET Core 2.0. I also use MySql.Data.EntityFrameworkCore.dll and Microsoft.AspNetCore.All (2.0.0-preview2-final). I have changed many times of librairy for MySql but without success.
Any idea why this always happen? What could be the cause?

Well, it turns out that you can't use MySql.Data.EntityFrameworkCore for .Net Core 2.0(for now). I had to go back to .Net Core 1.3 to make it work... We may be able to use it in a near futur tho!

Use Pomelo.EntityFrameworkCore.MySql 2.0.0.
Works fine for me with .NET Core 2.0

Add "Pomelo.EntityFrameworkCore.MySql" package.
in Stertup.cs & appsettings.json & DbContext :
services.AddDbContext<mvccoreContext>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection")
));
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=mvccore;User=root;Password=;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseMySql("");
}
}

MySql.Data.EntityFrameworkCore supports (and is only compatible with) EF Core 2.1. Using mismatched EF Core and DB provider libraries will result in errors similar to the one you reported.
If you need a MySQL EF Core provider that's compatible with EF Core 3.0, your only option right now is the 3.0.0-rc1 version of https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql (see the compatibility table at https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql#compatibility)! ).
Otherwise, if you want to stick with MySql.Data.EntityFrameworkCore you'll need to roll back to EF Core 2.1.

Related

Json body cannot convert from string to int dynamiclly after upgrade .netcore version

Before upgrade, the .Netcore version is 2.2, The string in JSON http request body can be converted to int in object like below Json
Post: api/ValidateMember
Host: XXXX
Content-Type: application/json
{
"id": "125324"
}
to object:
class RequestWithID
{
public int id {get;set;}
}
...
[HttpPost("api/ValidateMember")]
public bool ValidateMember(RequestWithID requestWithID)
{
...
}
This can work well before.
But after the .Netcore version upgrade to 3.1. there will always be an error with same request: The JSON value could not be converted to System.Int32. How to support the dynamic parsing of the string to int in .Netcore 3.1?
Explanation
Starting from ASP.NET Core 3.0 System.Text.Json serializer is used by default instead of previous Newtonsoft.Json.
Even though Newtonsoft.Json is slower (link 1 & link 2) than System.Text.Json it has many more features thus, making it sometimes more fitting choice as you experienced yourself.
Solution
In order to bring back the Newtonsoft.Json serializer add Microsoft.AspNetCore.Mvc.NewtonsoftJson package reference to your project and call AddNewtonsoftJson() in your Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
Also, when adding custom converters, ensure that you use Newtonsoft.Json namespace instead of System.Text.Json as both supply similarly named types.

"spawn UNKNOWN" error while debugging Visual Studio MVC application to Chrome

I'm creating a website using MVC (Visual Studio) and I get error "spawn unknown" when I debug using IIS Express. What is causing this error and how can I resolve it?
This is using Visual Studio 2017, but I suspect it could be something to do with the way it's configured on my computer, since this error doesn't occur on other computers.
This is the view:
#model WebApplication4.Models.Customer
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
And the controller:
namespace WebApplication4.Controllers
{
public class CustomerController : Controller
{
private ApplicationDbContext _context;
public CustomerController()
{
_context = new ApplicationDbContext();
}
// GET: Customer
public ActionResult Index(int id)
{
var customers = _context.Customers.ToList();
return View(customers);
}
}
And the model:
namespace WebApplication4.Models
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Membership MembershipType { get; set; }
}
public enum Membership
{
REGULAR,
SILVER,
GOLD
};
}
When I debug the solution with IIS Express, instead of opening Chrome and displaying the index page, I get a pop-up box from Microsoft Visual Studio, saying:
One or more errors occurred.
[debugger-for-chrome] Error processing "launch":spawn UNKNOWN
There are numerous questions on "spawn unknown" but none concerning C# or MVC (generally node.js or php - there is a question about the error in VS here but it's about a pop-up that appears after opening .php extension files.
According to this answer: Error: spawn UNKNOWN it looks like the issue is to do with using Chrome as the web browser. However is it possible to change IIS Express to use something other than Chrome?
It looks like the problem is when trying to debug a program from Visual Studio to Chrome with different privileges. When both VS and Chrome are run with admin privileges (or both as normal) the error doesn't show up.
For me, it was not privilege issue. The issue was that in my computer Chrome was installed at two different places:
C:\Users\[user]\AppData\Local\Google\Chrome\Application\chrome.exe
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
For my PC, the first one is broken executable, it's 64 bit one and somehow it've turned out to trash that doesn't work anymore, so I somehow managed to reinstall Chrome 32 bit onto the second path. Anyway, ended up to the state two Chrome executable coexists.
I totally forgot there is another one, and also in the PATH the second one is being added, so I didn't think the possibility VS code refers the one.
So in such case, you need to provide runtimeExecutable in your launch.json, like this:
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "https://example.com",
"runtimeArgs": ["--load-extension=${workspaceFolder}"],
"runtimeExecutable": "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
}
]
}

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}

Startup.cs error (ASP.Net Core configuration)

I am trying to set up an ASP.Net Core application to read in configuration settings from a json file. I am using VS2015 and .NetCore 1.0 (with .Net Core Tools preview 2). I am having problems getting a simple piece of boiler plate code to compile.
I am using the following code, which was published at
http://asp.net-hacker.rocks/2016/03/21/configure-aspnetcore.html
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights
// pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
However, the IDE/compiler complains that 'the name "Configuration" does not exist in the current context' (last line of code). The only suggestion from the IDE is to include Microsoft.Extensions.Configuration. However this is a namespace which does not contain an object or property named "Configuration".
In addition 'AddApplicationInsightsSettings' fails with does IConfigurationBuilder not contain a definition for AddApplicationInsightsSettings and no extension method AddApplicationInsightsSettings accepting a first argument of type IConfigurationBuilder could be found
Any suggestions please ?
Thanks
Simply add Configuration property to your Startup class, tutorial has missed this 'step':
public IConfigurationRoot Configuration { get; set; }
ConfigurationBuilder.Build() method just returns instance of IConfigurationRoot, that you should save, if need to get settings further in Startup class (in ConfigureServices method for example).
Regarding second error, looks like you didn't add the Application Insights dependency:
{
"dependencies": {
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0"
}
}

Resolve caste windsor failing

Recently upgraded to version 3.2.1 of castle windsor and receiving an error when attempting to resolve a service that previously didn't occur in version 3.0 of the windsor framework.
IWindsorContainer container = new WindsorContainer();
The following code no longer works
// Throws component not found exception
InstallerHelper.ProcessAssembliesInBinDirectory(
assembly => container.Register(
Classes
.FromAssembly(assembly)
.BasedOn<IWindsorInstaller>()
.WithService.FromInterface()
.LifestyleSingleton()
));
var installers = container.ResolveAll<IWindsorInstaller>();
container.Install(installers);
// Fails here, is it related to a hashcode mismatch in SimpleTypeEqualityComparer?
var credentialCache = container.Resolve<ICredentialCache>()
// works fine if explicity install installers individually
container.Install(new CredentialsInstaller());
var credentialCache = container.Resolve<ICredentialCache>()
Where ProcessAssembliesInBinDir is:
public static void ProcessAssembliesInBinDirectory(Action<Assembly> action)
{
var directoryName = GetDirectoryName();
foreach (var dll in Directory.GetFiles(directoryName, "*.dll"))
{
var fileInfo = new FileInfo(dll);
if (!IgnoreList.Any(x=>fileInfo.Name.StartsWith(x)))
{
var assembly = Assembly.LoadFile(dll);
action(assembly);
}
}
}
Where credential installer is:
public class CredentialsInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<ICredentidalCache>()
.ImplementedBy<CredentidalCache>()
.LifestyleSingleton()
);
// This works fine
var credentialCache = container.Resolve<ICredentialCache>()
}
}
Class implementation
public interface ICredentidalCache {}
public class CredentidalCache : ICredentidalCache{}
This is being run from an MVC application
version 4.5 of the .net framework
the credential installer lives inside another assembly, referenced by the website
using the Windsor source, the successful attempt to resolve occurs when the typeof(ICredentialCache).GetHashCode() is the same as what has been registered. For some reason when returning out of the installer the hashcode has changed for the type. Putting a debug line inside SimpleTypeEqualityComparer.GetHashCode(Type obj) shows that hashcodes are different for the same Type.
inspecting the container inside the debugger shows the ICredentialCache successfully installed.
Edit
Manage to move forward by manually registering installers, ie. not relying on the resolve<IwindsorInstaller>() and use container.install(new Installer(), ...). If i find out more I'll update the SO question.
This works fine for me:
public sealed class AppServiceFactory
{
...
public T Create<T>()
{
return (T)container.Resolve(typeof(T));
}
...
}
AppServiceFactory.Instance.Create<IYourService>();
The problem is caused by the InstallerHelper and how it goes about loading an assembly. This SO post pointed me in the right direction,
https://stackoverflow.com/a/6675227/564957
essentially the way the assembly was loaded was failing using Assembly.LoadFile(string fileName) was causing the problem, changing this to be Assembly.Load(string assemblyName) rectified the issue.
#Eric Lippert does a good job explaining
[when] loading an assembly by its path, and one via loading the same
assembly by its assembly name... reflection will
consider types from the two loadings of the same assembly to be
different types. Any assembly loaded from its path is considered to be
distinct from an assembly loaded by its assembly name.