关键词:
【中文标题】NET Core 6 使用 DTO 更新数据库记录时遇到问题【英文标题】:NET Core 6 Trouble updating a DB record using a DTO 【发布时间】:2022-01-12 19:03:35 【问题描述】:这是我第一次使用 DTO 将数据传输到数据库。我有这个使用 DTO 的 Create 方法(我不会显示该 DTO,因为这只是一个示例)并且工作正常:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CreateDTO dto)
DropDowns();
dto.Date_Added = DateTime.Now;
try
_context.Add(dto.ToWC_Inbox());
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
catch (Exception ex)
System.Diagnostics.Debug.WriteLine("It didn't work.");
System.Diagnostics.Debug.WriteLine(ex);
return View(dto.ToWC_Inbox());
创建 DTO 缺少一些在初始创建后需要输入的字段,因此我有一个单独的用于编辑的 DTO,如下所示:
public class ReviewDTO
public int ID get; set;
[MaxLength(50)]
public string First_Name get; set; = null!;
[MaxLength(50)]
public string Last_Name get; set; = null!;
[MaxLength(10)]
public string? Gender get; set;
[MaxLength(30)]
public string? Marital_Status get; set;
[MaxLength(4)]
public string? SSN get; set;
public DateTime? DOB get; set;
[MaxLength(100)]
public string? Address get; set;
[MaxLength(12)]
public string? Phone_Number get; set;
[MaxLength(4)]
public string Org_Number get; set; = null!;
public DateTime Hire_Date get; set;
[MaxLength(20)]
public string Job_Title get; set; = null!;
[MaxLength(50)]
public string Work_Schedule get; set; = null!;
public DateTime Injury_Date get; set;
[MaxLength(10)]
public string Injury_Time get; set; = null!;
[MaxLength(15)]
public string DOT_12 get; set; = null!;
[MaxLength(10)]
public string Start_Time get; set; = null!;
[MaxLength(30)]
public string Injured_Body_Part get; set; = null!;
[MaxLength(10)]
public string? Side get; set;
public bool Missing_Work get; set;
public DateTime? Missing_Work_Date get; set;
public DateTime? Begin_Missing_Date get; set;
[MaxLength(10)]
public string? Begin_Missing_Time get; set;
public DateTime? Return_To_Work_Date get; set;
public bool Doctors_Release get; set;
public bool? Treatment get; set;
[RequiredIf("Treatment == true", ErrorMessage = "Treatment Date is required.")]
public DateTime? Treatment_Date get; set;
[MaxLength(100)]
[RequiredIf("Treatment == true", ErrorMessage = "Treatment Provider is required.")]
public string? Treatment_Provider get; set;
[MaxLength(15)]
[RequiredIf("Treatment == true", ErrorMessage = "Treatment Provider Phone is required.")]
public string? Treatment_Provider_Phone get; set;
[MaxLength(50)]
[RequiredIf("Treatment == true", ErrorMessage = "Where first treated is required.")]
public string? Transport_First_Treatment get; set;
[MaxLength(50)]
[RequiredIf("Treatment == true", ErrorMessage = "The city of treatment is required.")]
public string? Transport_City get; set;
[MaxLength(250)]
public string Injury_Description get; set; = null!;
[MaxLength(250)]
public string? Equipment get; set;
[MaxLength(50)]
public string? Witness get; set;
[MaxLength(50)]
public string? Supervisor_Name get; set;
[MaxLength(15)]
public string? Supervisor_Phone get; set;
[MaxLength(250)]
public string? Questioned get; set;
[MaxLength(250)]
public string? Medical_History get; set;
public bool Inbox_Submitted get; set;
[RequiredIf("Inbox_Submitted == false", ErrorMessage = "The reason is required.")]
public string? Inbox_Reason get; set;
[MaxLength(250)]
public string? Comments get; set;
[MaxLength(254)]
public string User_Email get; set; = null!;
[MaxLength(254)]
public string Supervisor_Email get; set; = null!;
[MaxLength(254)]
public string Safety_Specialist_Email get; set; = null!;
[MaxLength(254)]
public string? Optional_Email get; set;
[MaxLength(254)]
public string? Optional_Email2 get; set;
[MaxLength(254)]
public string? Optional_Email3 get; set;
[MaxLength(254)]
public string? HDHR_Manager_Email get; set;
public int TX_EROI_Lag get; set;
public string? Claim_Ruling get; set;
public string? Injury_Type get; set;
public DateTime? TTD_Onset_Date get; set;
public DateTime? Restricted_RTW_Date get; set;
public DateTime? Full_Duty_RTW_Date get; set;
public bool Receiving_TTD get; set;
public DateTime? Date_TTD_Award_Notice get; set;
public DateTime? Claim_Ruling_Date get; set;
public DateTime? Med_Excuse_To get; set;
public string? Doctor get; set;
public DateTime? RTW_Email_Encova get; set;
public DateTime? Lost_Time_Start1 get; set;
public DateTime? Lost_Time_End1 get; set;
public DateTime? Lost_Time_Start2 get; set;
public DateTime? Lost_Time_End2 get; set;
public DateTime? Lost_Time_Start3 get; set;
public DateTime? Lost_Time_End3 get; set;
public string? Status get; set;
public string? HR_Comments get; set;
public string Add_User get; set; = null!;
public DateTime Date_Added get; set;
public string? HR_User get; set;
public DateTime? Date_Modified get; set;
public WC_Inbox ToCompletedWC_Inbox()
return new WC_Inbox
First_Name = this.First_Name,
Last_Name = this.Last_Name,
Gender = this.Gender,
Marital_Status = this.Marital_Status,
SSN = this.SSN,
DOB = this.DOB,
Address = this.Address,
Phone_Number = this.Phone_Number,
Org_Number = this.Org_Number,
Hire_Date = this.Hire_Date,
Job_Title = this.Job_Title,
Work_Schedule = this.Work_Schedule,
Injury_Date = this.Injury_Date,
Injury_Time = this.Injury_Time,
DOT_12 = this.DOT_12,
Start_Time = this.Start_Time,
Injured_Body_Part = this.Injured_Body_Part,
Side = this.Side,
Missing_Work = this.Missing_Work,
Missing_Work_Date = this.Missing_Work_Date,
Begin_Missing_Date = this.Begin_Missing_Date,
Begin_Missing_Time = this.Begin_Missing_Time,
Return_To_Work_Date = this.Return_To_Work_Date,
Doctors_Release = this.Doctors_Release,
Treatment = this.Treatment,
Treatment_Date = this.Treatment_Date,
Treatment_Provider = this.Treatment_Provider,
Treatment_Provider_Phone = this.Treatment_Provider_Phone,
Transport_First_Treatment = this.Transport_First_Treatment,
Transport_City = this.Transport_City,
Injury_Description = this.Injury_Description,
Equipment = this.Equipment,
Witness = this.Witness,
Supervisor_Name = this.Supervisor_Name,
Supervisor_Phone = this.Supervisor_Phone,
Questioned = this.Questioned,
Medical_History = this.Medical_History,
Inbox_Submitted = this.Inbox_Submitted,
Inbox_Reason = this.Inbox_Reason,
Comments = this.Comments,
User_Email = this.User_Email,
Supervisor_Email = this.Supervisor_Email,
Safety_Specialist_Email = this.Safety_Specialist_Email,
Optional_Email = this.Optional_Email,
Optional_Email2 = this.Optional_Email2,
Optional_Email3 = this.Optional_Email3,
HDHR_Manager_Email = this.HDHR_Manager_Email,
TX_EROI_Lag = this.TX_EROI_Lag,
Claim_Ruling = this.Claim_Ruling,
Injury_Type = this.Injury_Type,
TTD_Onset_Date = this.TTD_Onset_Date,
Restricted_RTW_Date = this.Restricted_RTW_Date,
Full_Duty_RTW_Date = this.Full_Duty_RTW_Date,
Receiving_TTD = this.Receiving_TTD,
Date_TTD_Award_Notice = this.Date_TTD_Award_Notice,
Claim_Ruling_Date = this.Claim_Ruling_Date,
Med_Excuse_To = this.Med_Excuse_To,
Doctor = this.Doctor,
RTW_Email_Encova = this.RTW_Email_Encova,
Lost_Time_Start1 = this.Lost_Time_Start1,
Lost_Time_End1 = this.Lost_Time_End1,
Lost_Time_Start2 = this.Lost_Time_Start2,
Lost_Time_End2 = this.Lost_Time_End2,
Lost_Time_Start3 = this.Lost_Time_Start3,
Lost_Time_End3 = this.Lost_Time_End3,
Add_User = this.Add_User,
Date_Added = this.Date_Added,
HR_User = this.HR_User,
Date_Modified = this.Date_Modified,
;
以及控制器方法:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ReviewDTO dto)
System.Diagnostics.Debug.WriteLine("ID: " + id);
System.Diagnostics.Debug.WriteLine("DTO ID: " + dto.ID);
DropDowns();
if (id != dto.ID)
return NotFound();
try
System.Diagnostics.Debug.WriteLine("Updating DB");
System.Diagnostics.Debug.WriteLine("ID again: " + id);
System.Diagnostics.Debug.WriteLine("DTO ID again: " + dto.ID);
_context.Update(dto.ToCompletedWC_Inbox());
await _context.SaveChangesAsync();
catch (DbUpdateConcurrencyException)
if (!WC_InboxExists(id))
return NotFound();
else
throw;
return RedirectToAction(nameof(Index));
问题在于,Edit 方法不是更新现有记录,而是使用更新后的信息创建一个全新的记录,并且不编辑旧记录。
那些打印语句用于确认 dto.ID 和从前一页收集的 id 匹配,并且确实如此。
在做了一些研究之后,我认为这是因为我需要从数据库中获取当前版本的记录,使用发布的值对其进行更改,然后将其保存回数据库,但我不完全确定如何这样做。
有人可以帮我弄清楚那部分吗?提前谢谢你。
【问题讨论】:
【参考方案1】:不应ToCompletedWC_Inbox
也映射Id
。比如:
public WC_Inbox ToCompletedWC_Inbox()
return new WC_Inbox
ID = this.ID, // assuming WC_Inbox has ID property
First_Name = this.First_Name,
....
【讨论】:
是的,这确实是我唯一缺少的东西。我很高兴这是一个简单的修复哈哈谢谢!带有 EF Core 的 ASP.NET Core - DTO 集合映射
...【发布时间】:2017-01-1923:51:23【问题描述】:我正在尝试使用(POST/PUT)一个DTO对象,其中包含从JavaScript到ASP.NETCore(WebAPI)的子对象集合,并将EFCore上下文作为我的数据源。主要的DTO类是这样的(当然是简化的):publ 查看详情
如何使用 ASP.NET Core 更新由依赖表组成的记录 [关闭]
】如何使用ASP.NETCore更新由依赖表组成的记录[关闭]【英文标题】:HowtoupdaterecordconsistingofdependenttablesusingASP.NETCore[closed]【发布时间】:2021-10-1617:03:57【问题描述】:我可以列出和创建记录,但不能更新记录。当我运行我的项目并... 查看详情
使用 Vue 和 ASP.NET Core DTO 模型的 JSON 对象的 JSON 序列化问题
】使用Vue和ASP.NETCoreDTO模型的JSON对象的JSON序列化问题【英文标题】:JSONserializationissuewithJSONOjectusingVueandASP.NETCoreDTOmodel【发布时间】:2020-11-2015:21:12【问题描述】:在我的Vuex商店中,我正在创建包含详细信息对象的数据对象,... 查看详情
在 POST API 中传递多个参数,而不使用 .Net Core MVC 中的 DTO 类
】在POSTAPI中传递多个参数,而不使用.NetCoreMVC中的DTO类【英文标题】:PostMultipleParametersWithoutDTOClass【发布时间】:2018-09-0814:00:42【问题描述】:我的网络项目有一个调用API的操作[HttpPost]publicasyncTask<IActionResult>ExpireSurvey(intid)... 查看详情
更新数据库:使用 mysql 的 asp.net core 错误
】更新数据库:使用mysql的asp.netcore错误【英文标题】:updatedatabase:errorasp.netcorewithmysql【发布时间】:2021-06-1817:38:28【问题描述】:我正在使用带有EF核心的mysql数据库。我使用IdentitySchema到我现有的MySql数据库,在迁移之后,更... 查看详情
使用 Core Data 插入/更新记录的最有效方法?
】使用CoreData插入/更新记录的最有效方法?【英文标题】:Mostefficientwaytoinsert/updaterecordswithCoreData?【发布时间】:2017-12-1123:46:53【问题描述】:我正在开发一个定期从服务器下载数据的应用程序。如果需要更新数据,我会使用类... 查看详情
在 asp.net core 中插入/更新记录时出错
】在asp.netcore中插入/更新记录时出错【英文标题】:Errorwhileinsert/updaterecordsinasp.netcore【发布时间】:2019-03-1421:52:21【问题描述】:当我尝试插入/更新记录时,出现以下错误。无法跟踪实体类型的实例,因为另一个实例\'Id\'具有... 查看详情
无法使用 ASP .NET Core 更新 SQL 位列
...是使用个人用户帐户选项自动设置的。用户帐户/角色的数据库表也是自动创建的。我创建了自己的继承自IdentityUser的ApplicationUser类,并为First 查看详情
使用 ADO.NET SqlDataAdapter 更新单个记录
...其链接到我的字段,并通过功能记录遍历并将更改保存回数据库。我想让用户选择使用对当前记录的更改来更新数据库,而不 查看详情
Entity Framework 6 使用正在更新的数据更新所有记录
...现实体框架6,但在执行记录更新时遇到问题。如果我在数据库中有2条记录,可以说:IdNameLastname1JasonMomoa2AquaMan 查看详情
在带有数据库的 ASP.NET Core 5.0 应用程序中使用 Serilog 实现日志记录
】在带有数据库的ASP.NETCore5.0应用程序中使用Serilog实现日志记录【英文标题】:ImplementLoggingUsingSerilogInASP.NETCore5.0ApplicationWithDatabase【发布时间】:2021-09-3023:02:38【问题描述】:在我的asp.netcore5.0应用程序中,每当我尝试使用serilo... 查看详情
无法在 ASP.NET Core 中更新数据库
】无法在ASP.NETCore中更新数据库【英文标题】:Can\'tupdatedatabaseinASP.NETCore【发布时间】:2020-12-0207:39:48【问题描述】:我使用Add-Migration和update-database创建了一个名为USERGOLD的表,它工作正常,该表是在SQLServer中创建的,但现在我... 查看详情
使用 .Net Core (.Net 5) 中的代码优先迁移将 ASPNetUsers 主键数据类型从 nvarchar 更新为 bigint
】使用.NetCore(.Net5)中的代码优先迁移将ASPNetUsers主键数据类型从nvarchar更新为bigint【英文标题】:UpdatingASPNetUsersprimarykeydatatypefromnvarchartobigintusingcodefirstmigrationin.NetCore(.Net5)【发布时间】:2021-09-1612:39:04【问题描述】:这是我将其... 查看详情
ASP.NET MVC Core/6:EF 6 脚手架错误
...:35:15【问题描述】:我正在使用EF6和MVCCore/6。我的模型和数据库上下文在单独的项目中,我使用DI将数据库上下文注入控制器。但是当我尝试使用EF6作为数据上下文类来搭建控制器时,我收到以下错误:错误运行所选代码生成器... 查看详情
使用 ASP.net 监控数据库中的更新和删除
】使用ASP.net监控数据库中的更新和删除【英文标题】:MonitorupdateanddeletionindatabaseusingASP.net【发布时间】:2012-04-1100:23:40【问题描述】:我在VB.net中使用网格来显示存储在MicrosoftAccess中的数据库记录,表格允许使用网格字段进行... 查看详情
如何在 ASP.NET Core 5 MVC (.NET 5) 中获取记录的用户数据?
...问题描述】:我目前正在开发一个ASP.NETCore5MVCWeb项目,我使用默认创建的单用户帐户生成模板进行用户管理。我已经应用了迁移,并且按预期工作正常。我需要登录用户,在.NET5单用户帐户模板Acc 查看详情
更新现有记录时出现 Entity Framework Core 错误
】更新现有记录时出现EntityFrameworkCore错误【英文标题】:EntityFrameworkCoreerroronupdatinganexistingrecord【发布时间】:2016-12-2012:45:11【问题描述】:在我的ASP.NET-CoreCodeFirstproject中,我在以下ActionMethod中的SaveChangesAsync()上收到以下错误... 查看详情
在 ASP.NET Core 中使用 Entity Framework 6
】在ASP.NETCore中使用EntityFramework6【英文标题】:UsingEntityFramework6inASP.NETCore【发布时间】:2017-09-3011:59:32【问题描述】:假设我有:用于.NETCore框架的ASP.NETCore独立WebAPI项目带有用于完整.NET框架的EF6数据模型的类库ASP.NETCore项目引... 查看详情