Use of UpdateAsync method ASP.NET Entity Framework

asp.net-mvc-4 c# entity-framework entity-framework-5 entity-framework-6

Question

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?

1
0
9/3/2015 1:36:48 PM

Accepted Answer

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);
    }
}
2
9/3/2015 1:38:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow