首页 > 解决方案 > 实体框架 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)

标签: c#entity-frameworkentity-framework-6shadowing

解决方案


推荐阅读