[英]How to update multiple tables using EF Core in single API method
I have 2 tables and 2 models for each table, Employee
and EmployeeHistory
.我有 2 个表和 2 个模型,每个表Employee
和EmployeeHistory
。 I have one API method in which I am checking if the employee details found, then insert old data from the Employee
table into the EmployeeHistory
table and then update the data in Employee
table with payload from API.我有一个 API 方法,我在其中检查是否找到员工详细信息,然后将Employee
表中的旧数据插入EmployeeHistory
表,然后使用来自 API 的有效负载更新Employee
表中的数据。
I have below code written for it.我为它编写了以下代码。 I am stuck at updating the EmployeeHistory
table.我一直在更新EmployeeHistory
表。 I can update the Employee
table with payload, but I'm not sure how to write code to update the EmployeeHisory
table.我可以使用有效负载更新Employee
表,但我不确定如何编写代码来更新EmployeeHisory
表。 Can you please help?你能帮忙吗? Thanks in advance.提前致谢。
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmpId { get; set; }
public int EmpName { get; set; }
public int Address{ get; set; }
public int MobNumber{ get; set; }
public EmployeeHistory EmployeeHistory { get; set; }
}
public class EmployeeHistory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int EmpId { get; set; }
public int OldAddress{ get; set; }
public int OldMobNumber{ get; set; }
public Employee Employee{ get; set; }
}`
[HttpPut]
public async Task<ActionResult> UpdateEmpDetails([FromBody] EmployeeDto employeeDto)
{
var emp = await _repository.GetEmployee(employeeDto.EmpId, employeeDto.EmpName);
//if member details found, update the record
if(emp != null)
{
//create new entry in EmployeeHistory table
var history = new EmployeeHistory();
history.OldAddress = emp.Address;
history.OldMobNumber = emp.MobNumber;
emp.EmployeeHistory = history;
//update record in Employee table
emp.Address = employeeDto.MemberId;
emp.MobNumber = employeeDto.FlagRefName;
await _dbcontext.SaveChanges();
return Ok();
}
}
I am getting an error at SaveChanges() function as
> An error occurred while saving the entity changes. See the inner exception for details. String or binary data would be truncated.
If Employee and EmployeeHistory are different you'll need to write a mapper to convert the DTO from an Employee to Employee history then insert that object to your EmployeeHistory table.如果 Employee 和 EmployeeHistory 不同,您需要编写一个映射器来将 DTO 从 Employee 转换为 Employee 历史,然后将 object 插入到 EmployeeHistory 表中。
Something along the lines of类似的东西
var history = new EmployeeHistory()
{
//Mapping logic between the DTOs
Property = employee.Property
......
};
_context.EmployeeHistory.Add(history);
_context.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.