c# - 实体框架 6 将 0 传递给可为空的 int
问题描述
Entity Framework 6 正在传递0
而不是在更新场景中null
使用。AddOrUpdate()
代码在插入场景中运行良好。
以下是代码:
public class RecordDetail
{
public int CreationUserId { get; set; }
public DateTime CreationDateTime { get; set; }
public int? ModifiedUserId { get; set; }
public DateTime? ModifiedDateTime { get; set; }
[ForeignKey(nameof(CreationUserId))]
public User CreationUser { get; set; }
[ForeignKey(nameof(ModifiedUserId))]
public User ModifiedUser { get; set; }
}
public class Role :RecordDetail
{
[Key]
public int RoleId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
public bool IsDeleted { get; set; }
public new int? CreationUserId { get; set; }
}
Role superAdmin = new Role
{
Name = "Super Admin",
IsDeleted = false,
CreationUserId = null,
CreationDateTime = currentDateTime
};
context.Roles.AddOrUpdate(x => x.Name, superAdmin);
context.SaveChanges();
出现以下错误:
SqlException: The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_USecurity.Role_USecurity.User_CreationUserId". The conflict occurred in database "DB", table "USecurity.User", column 'UserId'.
EF 产生的 SQL
UPDATE [USecurity].[Role]
SET [CreationUserId] = @0, [CreationDateTime] = @1
WHERE ([RoleId] = @2)
-- @0: '0' (Type = Int32)
-- @1: '9/13/2020 10:40:02 PM' (Type = DateTime2)
-- @2: '1' (Type = Int32)
解决方案
推荐阅读
- r - 在 R 中使用 reshape 将数据框从长更改为宽。未定义的列错误
- javascript - 如何定期重新渲染反应组件
- c# - C# Selenium 4:设置请求拦截
- kotlin - 从泛型类型参数中删除可空性
- html - 与模块冲突 - 带类的 div 消失
- javascript - 在 ejs/express 中调用 setInterval() 并查询 db
- python - 使用 NSTask 在 Objective C 中运行 SH 脚本比从 Terminator 直接执行脚本慢
- android - 片段无法处理许多编辑文本
- php - 缺少路由资源显示所需的参数
- javascript - toISOString() 从值中减去天