【发布时间】:2018-02-08 06:30:38
【问题描述】:
我正在开发一个应用程序,我通过 Code First 方法使用 .Net Core 2、EF Core 和 MySQL 作为数据库服务器。
我有 2 张桌子:
- 用户
- 员工
User 表是主表,其中包含用户信息,Employee 表是子表,其中有一个 ID_User 列,如下所示:
public class User : BaseEntity
{
public int ID_User { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public virtual ICollection<Employee> Employees{get;set;}
}
public class Employee : Entity
{
public int ID_Employee { get; set; }
public string Name { get; set; }
public int ID_User { get; set; }
public virtual User User { get; set; }
}
当我使用上述映射并且我在两个表中都有足够的数据时,一切正常。
现在,我想将 Employee 表中的列 ID_User 设为 可为空
为了实现此更改,我对模型进行了以下更改:
public class Employee : Entity
{
public int ID_Employee { get; set; }
public string Name { get; set; }
public int? ID_User { get; set; }
public virtual User User { get; set; }
}
在映射文件中:
builder.HasOne(x=>x.User).WithMany(y=>y.Employees).HasForeignKey(z=>z.ID_User).IsRequired(false);
运行dotnet ef migrations add empuser 命令后,它生成了以下迁移代码:
migrationBuilder.DropForeignKey(
name: "FK_Employee_User_ID_User",
table: "Employee");
migrationBuilder.AlterColumn<int>(
name: "ID_User",
table: "Employee",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AddForeignKey(
name: "FK_Employee_User_ID_User",
table: "Employee",
column: "ID_User",
principalTable: "User",
principalColumn: "ID_User",
onDelete: ReferentialAction.Restrict);
现在当我运行dotnet ef database update 时,它给了我以下错误:
您的 SQL 语法有错误;检查手册 对应于您的 MySQL 服务器版本,以便使用正确的语法 在第 1 行的“CONSTRAINT
FK_Employee_User_ID_User”附近
请帮忙。
谢谢
【问题讨论】:
-
您可以尝试使用其他一些提供程序,例如内存,这样您就可以将问题缩小到提供程序或mysql
-
@NevilleNazerane 你能解释一下你想让我尝试什么吗?
-
对于 mysql,你会使用
MySql.Data.EntityFrameworkCore。现在,卸载它并再次安装Microsoft.EntityFrameworkCore.InMemory和dotnet ef database update。如果您仍然看到问题,这与您的模型代码有关,否则它是特定于 mysql 的问题 -
@NevilleNazerane 实际上该项目非常大,并且具有多层方法和以下存储库/UOW 模式。如果我进行此更改,我将不得不在许多地方进行修改,这将花费大量时间。如果我们对此有任何其他选择,那就太好了。从错误消息中可以清楚地看出问题出在 MySql 上,因为与 SQL server 一起使用时相同的代码正在运行。
-
我使用的是官方的 MySQL 连接器,这导致了这个问题。当我切换到 Pomelo 之后,它工作正常。谢谢大家的建议
标签: mysql .net entity-framework asp.net-core .net-core