实体框架6将0传递给可为null的int

问题描述

在更新方案中使用0时,实体框架6正在传递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)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)