Per favore, come possiamo evitare che EF.core provi ad inserire / aggiornare tabelle con chiavi esterne quando creiamo una nuova entità primaria?
Questa eccezione è generata:
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.
Il mio codice è il seguente:
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; }
}
Qualsiasi tentativo di creare un nuovo Offence
dà errori, poiché EF.core tenta di eseguire inserimenti per le proprietà di navigazione correlate:
public Guard Guard { get; set; }
public Salary Salary { get; set; }
public Site Site { get; set; }
public Penalty Penalty { get; set; }
Come possiamo evitare questo?
Modifica: crea e aggiorna il codice
[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);
}
Sembra che le tue proprietà di navigazione abbiano dei valori, per favore controlla che la tua proprietà di navigazione abbia un riferimento null prima di salvare; La logica di salvataggio di EF Core tenta di salvare le proprietà di navigazione se hanno un valore.
Fammi sapere se questo è utile
Per farlo funzionare, ho dovuto null-out
le proprietà di navigazione prima di salvare.
Tuttavia, se si invia nuovamente l'oggetto iniziale con CreatedAtRoute
, è necessario memorizzare nella cache le proprietà nulled-out
e aggiungerle nuovamente prima di tornare:
Codice effettivo:
[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;
var _g = o.Guard;
var _p = o.Penalty;
var _s = o.Site;
o.Guard = null;
o.Penalty = null;
o.Site = null;
await db.AddAsync(o);
await db.SaveChangesAsync();
o.Guard = _g;
o.Penalty = _p;
o.Site = _s;
return CreatedAtRoute("GetOffenceAsync", new { id = o.offence_id }, o);
}