使用 UpdateAsync 方法 ASP.NET Entity Framework

Use of UpdateAsync method ASP.NET Entity Framework

我的实体如下所示:

public class AddPatientReportDentalChartInput : IInputDto
{
    [Required]
    [MaxLength(PatientReportDentalChart.TeethDesc)]
    public string Image { get; set; }

    [Required]
    public virtual int PatientID { get; set; }
    [Required]
    public virtual  int TeethNO { get; set; }
    public string SurfaceDefault1 { get; set; }
    public string SurfaceDefault2 { get; set; }
    public string SurfaceDefault3 { get; set; }
    public string SurfaceDefault4 { get; set; }
    public string SurfaceDefault5 { get; set; }
}

我想更新的方法是:

public async Task addPatientReportDentalChart(AddPatientReportDentalChartInput input)
{
    var pid = input.PatientID;
    var chartdetails = _chartReportRepository
                        .GetAll()
                        .WhereIf(!(pid.Equals(0)),
                                   p => p.PatientID.Equals(pid)).ToList();

    if (chartdetails.Count>0)
    {
        //Update should be apply here 
        //please suggest me the solution using updatesync
    }
    else 
    { 
        var patientinfo = input.MapTo<PatientReportDentalChart>();
        await _chartReportRepository.InsertAsync(patientinfo);
    }
}

当我想更新现有实体时,InsertAsync 的等价物是什么?是否有 UpdateAsync 等效方法?

更新 Entity Framework 中的实体需要您检索记录,更新它,然后保存更改。大致如下所示:

public async Task AddPatientReportDentalChartAsync(AddPatientReportDentalChartInput input)
{
    var pid = input.PatientID;
    var chartdetails = _chartReportRepository
                        .GetAll()
                        .WhereIf(!(pid.Equals(0)),
                                   p => p.PatientID.Equals(pid)).ToList();

    if (chartdetails.Count > 0)
    {
        var entity = await _chartReportRepository
                                .YourTableName
                                .FindAsync(entity => entity.SomeId == matchingId);

        entity.PropertyA = "something"
        entity.PropertyB = 1;
        await _chartReportRepository.SaveChangesAsync();
    }
    else 
    { 
        var patientinfo = input.MapTo<PatientReportDentalChart>();
        await _chartReportRepository.InsertAsync(patientinfo);
    }
}

如果您使用的是 .NET CORE 3.1,请试试这个

 public async Task<int> UpdateChat(MChat mChat)
    {
        try
        {
            return await Task.Run(() =>
            {
                BDContext.Chat.Update(new Chat
                {
                    Id = mChat.id,
                    UsuarioIdInicia = mChat.usuarioIdInicia,
                    UsuarioIdFinaliza = mChat.usuarioIdFinaliza,
                    EstadoChatId = mChat.estadoChatId
                });
                return BDContext.SaveChanges();
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine(Constantes.ERROR_DETECTADO + ex.InnerException.ToString());
            return Constantes.ERROR_1;
        }

    }