c# - 使用 UpdateAsync 方法 ASP.NET Entity Framework

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

最佳答案

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

关于c# - 使用 UpdateAsync 方法 ASP.NET Entity Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32376692/

相关文章:

c# - 私有(private)属性(property)的设定值

c# - 从服务器端的路由值解析 url

C# Windows 窗体应用程序 - 使用 gmail smtp 发送电子邮件

asp.net-mvc - MVC + EF DB-First 单元测试

asp.net-mvc-4 - MVC 路由不起作用

c# - 从服务中检索 Json 并传递给 ApiController

c# - 如何使用 Datatable 的 Compute 方法在运行时评估 bool 表达式?

c# - Entity Framework : Filtering navigation-property data

entity-framework - 处理从 Entity Framework 中的存储过程返回的多个结果集

c# - 带有输出缓存的私有(private) Controller 操作结果