如何解决更新语句的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;
}
}
表-
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。