John John - 1 month ago 10
C# Question

How to resolve context id

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

Answer

try to use it EmployeeId from the saved one, i.e.

var report = new Report {
        CaseID = c.Id, 
        EmployeeID = employee.ID
    }; 

when it is saved it should get the ID directly.

Question, is there any specific reason why you didn't use "virtual" keyword in your code for lazy loading?

And I'd also consider what would happen if context.reports.add(report) failed but employee add hadn't failed.