我正在开发一个使用 .Net Core 2、EF Core 和 MySQL 数据库服务器的应用程序,采用 Code First 方法。
我有两个表:
- User(用户)
- Employee(员工)
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 服务器版本相对应的手册,以获取使用正确语法的方法。 错误出现在 'CONSTRAINT
FK_Employee_User_ID_User
' 行附近,位于第一行。
谢谢。
Employee.User
上的virtual
关键字。 如果有帮助的话,我在这里的项目中正在为LicenseId
和SyntaxId
进行类似的设置:https://github.com/collinbarrett/FilterLists/blob/master/src/FilterLists.Data/Entities/FilterList.cs - Collin Barrett