亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Automapper 簡潔地插入/更新/刪除可枚舉的子實體

使用 Automapper 簡潔地插入/更新/刪除可枚舉的子實體

C#
繁星coding 2021-06-24 18:06:58
我正在開發一個 ASP.Net MVC 應用程序,我有一個“報告”對象,它具有相關的可枚舉項,例如日程表和注釋。使用 AutoMapper,可以輕松地從報表實體轉換為視圖模型并返回,但是當我嘗試將報表對象(從視圖模型映射到現有實體)保存回數據庫時遇到問題。更具體地說,我似乎無法使用 automapper 簡潔地更新現有實體、插入新實體和刪除舊實體。例如,每當我將計劃從視圖模型映射到報告實體時,它都會刪除現有計劃,然后創建新計劃(具有遞增索引)。這是我的代碼:public class ScheduleViewModel{    public int ScheduleID { get; set; }    public int ReportID { get; set; }    public int Month { get; set; }    public int Day { get; set; }    public string Description { get; set; }}public class ReportViewModel{    public int ReportID { get; set; }    public List<ScheduleViewModel> Schedules { get; set; }    public void Save()    {        dbContext db = new dbContext();        Report original = db.Reports.SingleOrDefault(o => o.ReportID == ReportID);        var config = new MapperConfiguration(cfg =>        {            cfg.CreateMap<ReportViewModel, Report>();        });        config.AssertConfigurationIsValid();        var mapper = config.CreateMapper();        mapper.Map(this, original);        db.SaveChanges();    }}我的 Report 對象有一個關系鍵(和一個“Schedules”導航屬性),所以一切都從我的視圖模型成功映射到“原始”報告。新計劃的 ScheduleID 為 0,因為它們尚未分配,并且它們使用自動增量添加到數據庫中,這正是我想要的?,F有計劃在映射到“原始”報告對象時保持其 ScheduleID,但一旦調用 SaveChanges,就會收到遞增的 ID。據我了解,無論視圖模型 ID 屬性是否與數據庫中的主鍵匹配(在這種情況下,它是 ReportID 和 ScheduleID 的組合),我都會將新的計劃附加到上下文中。有沒有一種干凈的方法,使用某種 ForMember(report => report.Schedules),如果視圖模型對象可以映射到現有鍵,則使實體框架理解不會破壞我現有實體的表達式?我正在尋找功能類似于下面代碼的東西,但由于我將有許多可枚舉屬性附加到我的報表對象,我不想為每個屬性維護這些部分:foreach (Schedule schedule in db.Schedules.Where(s => s.ReportID == this.ReportID)){    ScheduleViewModel svm = this.Schedules.FirstOrDefault(s => s.ScheduleID == schedule.ScheduleID);    //Update Existing    if (svm != null)        db.Entry(schedule).CurrentValues.SetValues(svm);    //Delete Missing    else        db.Entry(schedule).State = System.Data.Entity.EntityState.Deleted;}
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 188 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號