I have a context called companyContext. There are Three tables Reports, Logs and Employees. I'm trying to add another Employee to my table of employees, but I have a table Reports that keeps track of which employees belong to cases (CaseID) and if there is a log of what happened. After I add the employee to the context I need to add a Report with the just added employee id (which is a primary key, so its not getting passed with the employee variable). The only way I can think of doing it is getting a current count of the employees table. This seems like bad practice. Is there a better way to achieve this?
Clarify:
I'm sending a Employee employee object from my client. Name and Code are the only things not null in the object.
public async Task<IActionResult> addEmployee([FromBody] Employee employee) {
try {
context.Employees.Add(employee);
var c = storage.GetCase(employee);
var employeeId = await context.Employees.CountAsync();
var report = new Report {
CaseID = c.Id,
EmployeeID = employeeId,
};
context.Reports.Add(report);
return Json(employee);
} catch (Exception ex){
logger.LogError("Employee exception in Company Controller", ex);
return BadRequest("Unexpected Error");
}
}
Models
public class Log
{
public int ID { get; set; }
public string Input { get; set; }
public string Tag { get; set; }
public DateTime LogDate { get; set; }
public ICollection<Report> Reports { get; set; }
}
public class Employee
{
public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public ICollection<Report> Reports { get; set; }
}
public class Report
{
public int ID { get; set; }
public string CaseID { get; set; }
public int EmployeeID { get; set; }
public int? LogID { get; set; }
public Employee Employee { get; set; }
public Log Log { get; set; }
}
Soultion
public async Task<IActionResult> addEmployee([FromBody] Employee employee) {
try {
context.Employees.Add(employee);
await context.SaveChangesAsync();
var c = storage.GetCase(employee);
var report = new Report {
CaseID = c.Id,
EmployeeID = employee.ID,
};
context.Reports.Add(report);
await context.SaveChangesAsync()
return Json("Worked");
} catch (Exception ex){
logger.LogError("Employee exception in Company Controller", ex);
return BadRequest("Unexpected Error");
}
}