更新语句的Savechanges在实体框架核心3.1中给出了错误

问题描述

我在更新实体时遇到Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded错误。

如果我要添加新实体,则可以正常工作。我尝试了其他文章中提到的解决方案来对其进行修复(例如检查主键是否存在,在实体中添加[key]等),但该解决方案对我不起作用。

注意-我先创建了数据库,然后对其进行了脚手架安装。另外,我的实体中的注释部分(添加键)也无法正常工作。请帮忙

以下是我的代码-

实体-

public partial class Groups
{
    //[Key]
    //[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string GroupName { get; set; }
    public int? AccountId { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime? ModifiedDate { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? CreatedDate { get; set; }
    public byte[] Timestamp { get; set; }
}

逻辑-

public class SaveGroupHandler : BaseHandler,IRequestHandler<SaveGroupCommand,saveGroupResponse>
{
    public SaveGroupHandler(ZTT2020Context dbContextSql,IMediator mediator) : base(dbContextSql,mediator)
    {
    }
    public async Task<SaveGroupResponse> Handle(SaveGroupCommand request,cancellationToken cancellationToken)
    {
        var entity = new Groups
        {
            Id=request.GroupId,GroupName = request.GroupName,AccountId = request.AccountID,ModifiedBy = null,ModifiedDate = null,CreatedBy = null,CreatedDate = DateTime.Now
        };
        if(request.GroupId==0)
        {
            _dbContextSql.Groups.Add(entity);
        }
        else
        {
            _dbContextSql.Groups.Update(entity);
            _dbContextSql.Entry(entity).Property(s => s.CreatedDate).IsModified = false;
        }
        await _dbContextSql.SaveChangesAsync();
        var resultentity = await _dbContextSql.Groups.Where(x => x.Id == entity.Id).SingleAsync();
        var response = resultentity.ToResponse();
        return response;
    }
}

表-

enter image description here

解决方法

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...