实体框架无法插入数据库,因为 IsDeleted 列设置为 false 时为空

问题描述 投票:0回答:1

如何解决此异常?

无法将 NULL 值插入表“snapshot2_new.dbo.Workflows”的“IsDeleted”列;列不允许为空。插入失败

它发生在这个方法中:

public async Task<Workflow> CopyWorkflow(int id, int userId)
{
    var wf = await this._context.Workflows
                    .Include(w => w.WorkflowStages)
                        .ThenInclude(s => s.Questions)
                    .Include(w => w.WorkflowStages)
                        .ThenInclude(s => s.StageTimeLimits)
                    .Include(w => w.WorkflowStages)
                        .ThenInclude(s => s.RequiredDocumentation)
                    .Include(w => w.WorkflowStages)
                        .ThenInclude(s => s.DocumentCategories)
                    .Include(w => w.WorkflowStages)
                        .ThenInclude(s => s.RolesCanUpdateStage)
                    .AsNoTracking()  // Ensure no tracking to prevent issues with original entity
                    .AsSplitQuery()
                    .FirstOrDefaultAsync(w => w.Id == id);

    if (wf == null)
    {
        throw new Exception("Workflow not found.");
    }

    // Reset the identity column and other properties
    wf.Id = 0;  // Reset the Id so the database can assign a new one
    wf.IsRetired = false;
    wf.IsDeleted = false;
    wf.DateCreated = DateTime.Now;
    wf.DateUpdated = DateTime.Now;

    // Add the modified workflow to the context
    _context.Workflows.Add(wf);
    await _context.SaveChangesAsync(); // Use async save

    return wf;
}

我在

SaveChangesAsync
之前停止了调试器,并且
wf
具有
false
的值
IsDeleted

这是实体框架生成的查询

[23:44:36 ERR] Failed executing DbCommand (20ms) [Parameters=[@p0='?' (DbType = DateTime2), @p1='?' (DbType = DateTime2), @p2='?' (DbType = Boolean), @p3='?' (DbType = Boolean), @p4='?' (DbType = Boolean), @p5='?' (DbType = Boolean), @p6='?' (DbType = Int32), @p7='?' (DbType = Int32), @p8='?' (Size = 4000), @p9='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
SET NOCOUNT ON;
INSERT INTO [Workflows] ([DateCreated], [DateUpdated], [IsEnabledDocumentTemplates], [IsQVAccountsProductionRequired], [IsRetired], [IsTemplate], [ManagingAgentId], [UserId], [WorkflowTitle], [WorkflowTypeId])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9);
SELECT [WorkflowId], [IsDeleted]
FROM [Workflows]
WHERE @@ROWCOUNT = 1 AND [WorkflowId] = scope_identity();
.net entity-framework
1个回答
0
投票

问题出在以下代码上:

entity.Property(t => t.IsDeleted)
    .HasDefaultValue(false);

propery 配置错误,这就是 IsDeleted 未包含在 EntityFramework 生成的查询中的原因

将代码修改为这些解决了问题:

entity.Property(t => t.IsDeleted)
    .IsRequired(true);
© www.soinside.com 2019 - 2024. All rights reserved.