Please how can we prevent EF.core from trying to insert/update foreign-key tables when we create a new primary entity?
This Exception is thrown:
SqlException: Cannot insert explicit value for identity column in table 'clients' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value for identity column in table 'guards' when IDENTITY_INSERT is set to OFF.
Cannot insert explicit value for identity column in table 'penalties' when IDENTITY_INSERT is set to OFF.
My code is as follows:
public class Offence
{
[Key]
public Int32 offence_id { get; set; }
public Int32? guard_id { get; set; }
public Int32? penalty_id { get; set; }
public DateTime? dt_recorded { get; set; }
public Int32? salary_id { get; set; }
public Decimal? amount { get; set; }
public String status { get; set; }
public Int32? site_id { get; set; }
public Guard Guard { get; set; }
public Salary Salary { get; set; }
public Site Site { get; set; }
public Penalty Penalty { get; set; }
}
Any attempt to create a new Offence
gives errors, as EF.core tries to run inserts for the related navigation properties:
public Guard Guard { get; set; }
public Salary Salary { get; set; }
public Site Site { get; set; }
public Penalty Penalty { get; set; }
How can we prevent this?
Edit: Create and update code
[HttpPost]
public async Task<IActionResult> Create([FromBody] Offence o)
{
if (o == null)
{
return BadRequest();
}
o.last_modified_by = int.Parse(((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value);
o.last_modified = DateTime.Now;
await db.AddAsync(o);
await db.SaveChangesAsync();
return CreatedAtRoute("GetOffenceAsync", new { id = o.offence_id }, o);
}
db
is aDbContext
``` private readonly RSGContext db; public OffencesController(RSGContext context) { db = context; } ```