【发布时间】:2018-04-03 05:10:07
【问题描述】:
请问,当我们创建新的主实体时,如何防止 EF.core 尝试插入/更新外键表?
抛出此异常:
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; }
}
任何创建新 Offence 的尝试都会出错,因为 EF.core 会尝试为相关导航属性运行插入:
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);
}
【问题讨论】:
-
你能显示你的更新代码吗?
-
@H.Herzl 我添加了创建和更新代码,以及我遇到的错误
-
我要看看db是什么类型,我猜是DbSet
-
db是DbContext``` 私有只读 RSGContext 数据库;公共 OffencesController(RSGContext 上下文){ db = 上下文; } ``` -
好的,您的导航属性似乎有值,请在保存之前检查您的导航属性是否有空值,顺便说一下,为什么您不使用 db.Set
() 代替db.Add?
标签: entity-framework-core ef-core-2.0