Use of UpdateAsync method ASP.NET Entity Framework

18,849

Solution 1

Updating an entity in Entity Framework requires you to retrieve the record, update it and then save changes. It will look roughly like this:

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);
    }
}

Solution 2

Try this if you're using .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;
        }

    }
Share:
18,849
Ashutosh Adarsh
Author by

Ashutosh Adarsh

I am a Software Developer of ASP.NET and MVC

Updated on June 05, 2022

Comments

  • Ashutosh Adarsh
    Ashutosh Adarsh almost 2 years

    My entity looks as follows:

    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; }
    }
    

    And the method by which i want to update is:

    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);
        }
    }
    

    What is the equivalent of InsertAsync when I want to update an existing entity? Is there an UpdateAsync equivalent method?

    • Ashutosh Adarsh
      Ashutosh Adarsh over 8 years
      I want simply to update in database using updateSync method like Inserting await _chartReportRepository.InsertAsync(patientinfo);
    • Yuval Itzchakov
      Yuval Itzchakov over 8 years
      Use FindAsync to look for the entity, modify it, and use SaveChangesAsync.
    • Ashutosh Adarsh
      Ashutosh Adarsh over 8 years
      Will you please suggest me with above code ?
    • Yuval Itzchakov
      Yuval Itzchakov over 8 years
      See my answer below.
  • Ashutosh Adarsh
    Ashutosh Adarsh over 8 years
    Thank You so much for your answer. You saved my whole day. Thank you :)
  • Serhii
    Serhii over 3 years
    please don't do this. You just block the thread by calling a synchronous BDContext.SaveChanges(). In case you really want to achieve it, please use .SaveChangesAsync() without Task.Run
  • Ramiro G.M.
    Ramiro G.M. over 3 years
    My friend Task.Run allows u to await...this means it's not gonna block the main thread since it's NOT working synchronously...I could have used .SaveChangesAsync(), but I rather have the entire logic running asynchronously, in case I need to add even more logic...
  • Robba
    Robba about 3 years
    @JohnDoe is right, you're just throwing away a thread by doing it this way. Simply using await on the SaveChangesAsync will give you the same results in terms of 'blocking the main thread', but without using 2 threads to do it.