제발 우리가 새 기본 엔터티를 만들 때 EF.core가 외래 키 테이블을 삽입 / 업데이트하지 못하게 할 수 있습니까?
이 예외가 Throw됩니다.
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.
내 코드는 다음과 같습니다.
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; }
}
EF.core가 관련 탐색 속성에 대한 삽입을 실행하려고 시도 할 때 새로운 Offence
를 만들려고하면 오류가 발생합니다.
public Guard Guard { get; set; }
public Salary Salary { get; set; }
public Site Site { get; set; }
public Penalty Penalty { get; set; }
어떻게 우리가 이것을 막을 수 있습니까?
편집 : 코드 생성 및 업데이트
[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);
}
네비게이션 속성에 값이있는 것 같습니다. 저장하기 전에 네비게이션 속성에 null 참조가 있는지 확인하십시오. EF 코어 저장 로직은 값이 있으면 탐색 속성을 저장하려고합니다.
이게 도움이되는지 알려줘.
이 기능을 사용하려면 저장하기 전에 탐색 속성을 null-out
해야했습니다.
그러나 CreatedAtRoute
초기 객체를 다시 보내는 경우, 반환하기 전에 nulled-out
속성을 캐싱하고 다시 추가해야합니다.
실제 코드 :
[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);
}