我有一个 .NET Core 项目(针对 .NET 4.6),我必须同时使用 EF Core 和 EF 6。由于我也使用 MySQL,所以我的 project.json
看起来像这个:
{
...
"dependencies": {
"EntityFramework": "6.1.3", // For EF 6
"MySql.Data.Entity": "6.9.9", // For EF 6 and MySQL
"Pomelo.EntityFrameworkCore.MySql": "1.1.0", // For EF Core
...
},
"frameworks": {
"net461": {}
},
...
}
问题是当我尝试像这样使用 MySqlConnection
类时:
var connection = new MySqlConnection(connectionString);
我收到以下错误:
The type 'MySqlConnection' exists in both
'MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' and
'MySqlConnector, Version=0.7.2.0, Culture=neutral, PublicKeyToken=null'
有没有办法让我准确指定我想使用哪个库MySqlConnection
,或者还有其他方法来解决这个问题吗?
这些是我的限制:
- 我需要 EF Core,因为我们使用
ASP.NET Core Identity
(以及其他仅使用 EF Core 的 .NET Core 库) - 我需要 EF 6,因为我们发现目前没有适用于 MySQL 的 EF Core 实现足以满足我们的所有需求。
- 由于我们使用 MySQL,因此我需要对 EF 6 使用
MySql.Data.Entity
,对 EF Core 使用Pomelo.EntityFrameworkCore.MySql
。我们尝试过将其他库用于 EF Core,但它们存在很多错误。我们发现 Pomelo 是最稳定的。
编辑:
我认为原因是 Pomelo.EntityFrameworkCore.MySql
引用了 MySqlConnector
,它具有命名空间/类 MySql.Data.MySqlClient.MySqlConnection
,所以执行MySql.Data.Entity
。
最佳答案
你可以在你的project.json中做类似的事情
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50",
"dependencies": {
// Your .NET Core dependencies
}
},
"net461": {
"dependencies": {
// Your .NET 4.6.1 dependencies
}
}
}
然后在你的代码中你可以做一个像这样的界面:
#if NET461
// put your EF usings for .NET 4.6.1 here
#else
// put your EFCore usings for .NET Core
#endif
public interface IDatabase
{
void Initialize();
DbContext GetContext();
}
然后创建两个继承于IDatabase
接口(interface)的对象。一个用于 .NET 4.6.1,另一个用于 .NET Core
.NET 4.6.1
#if NET461
// put your usings for EF for net461
public class Database461 : IDatabase
{
private DbContext context;
public Database461(DbContext context)
{
// ...
}
public void Initialize()
{
// initialize stuff if you want
}
public DbContext GetContext()
{
return this.context;
}
}
#endif
.NET Core*
// notice here that i've put a "!" that means "not"
#if !NET461
// put your usings for EF Core
public class DatabaseNetCore : IDatabase
{
private DbContext context;
public DatabaseNetCore (DbContext context)
{
// ...
}
public void Initialize()
{
// initialize stuff if you want
}
public DbContext GetContext()
{
return this.context;
}
}
#endif
最后,在您的应用中,您将在启动时使用上述两个对象之一初始化您的 IDatabase
对象,并执行您想要的任何操作。
// At startup, somewhere in your app...
static IDatabase database;
public InitializeDatabase()
{
#if !NET461
database = new DatabaseNetCore(...);
#else
database = new Database461(...);
#endif
database.Initialize();
}
希望对你有帮助
关于mysql - 处理 .NET Core project.json 中的依赖冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490074/