使用UpdateAsync方法ASP.NET实体框架

时间:2015-09-03 13:13:52

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

我的实体如下所示:

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等效方法?

2 个答案:

答案 0 :(得分:2)

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

<i class="icon ion-checkmark answer-correct" ng-if="submitted && answers[$parent.$parent.$index * 7 + $parent.$index].correct"></i>

答案 1 :(得分:1)

如果使用的是.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;
        }

    }