我已经在这里阅读了有关该问题的其他问题,并且他们说他们忘了包含对象的ID。我在对象中有id:
但我仍然会收到错误:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException:数据库 操作预计会影响1行,但实际上影响了0行。 自实体加载以来,数据可能已被修改或删除。
控制器:
[HttpPut("update")]
public async Task<IActionResult> Update([FromBody] ProgramModel model)
{
var id = await _programService.UpdateAsync(model, _claimsService.GetSubIdFromClaims(User));
if (id == 0)
{
return BadRequest();
}
return Created(string.Empty, new { id });
}
商务:
public async Task<int> UpdateAsync(ProgramModel model, string modifiedBy)
{
_repository.Update(_mapper.Map<Program>(model), modifiedBy);
return await _repository.SaveAsync();
}
Automapper:
public class ProgramProfile : Profile
{
public ProgramProfile()
{
CreateMap<Program, ProgramModel>()
.ReverseMap()
.ForMember(dest => dest.Id, opts => opts.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opts => opts.MapFrom(src => src.Name))
.ForMember(dest => dest.Type, opts => opts.MapFrom(src => src.Type))
.ForMember(dest => dest.Length, opts => opts.MapFrom(src => src.Length))
.ForMember(dest => dest.TimesPerWeek, opts => opts.MapFrom(src => src.TimesPerWeek))
.ForAllOtherMembers(m => m.Ignore());
//CreateMap<ProgramModel, Program>();
}
}
存储库:
public virtual void Update<TEntity>(TEntity entity, string modifiedBy = null)
where TEntity : class, IEntity
{
entity.ModifiedDate = DateTime.UtcNow;
entity.ModifiedBy = modifiedBy;
context.Set<TEntity>().Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
public virtual Task<int> SaveAsync()
{
return context.SaveChangesAsync();
}
计划类:
public class Program : EntityMaximum
{
public string Name { get; set; }
public byte Type { get; set; }
public int Length { get; set; }
public byte TimesPerWeek { get; set; }
}
public class EntityMaximum : Entity<int>
{
public bool IsActive { get; set; }
}
public abstract class Entity<T> : EntityMinimum, IEntity<T>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public T Id { get; set; }
object IEntity.Id
{
get => Id;
set => throw new NotImplementedException();
}
private DateTime? _createdDate;
[DataType(DataType.DateTime)]
public DateTime CreatedDate
{
get => _createdDate ?? DateTime.UtcNow;
set => _createdDate = value;
}
[DataType(DataType.DateTime)]
public DateTime? ModifiedDate { get; set; }
public string ModifiedBy { get; set; }
}
public class EntityMinimum : IEntityMinimum
{
public bool IsDeleted { get; set; }
[Timestamp]
public byte[] Version { get; set; }
public string CreatedBy { get; set; }
}