本文介绍了当IDENTITY_INSERT设置为OFF时,从实体框架核心获取错误“无法在表'组织'中为标识列插入显式值”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有2张桌子Hi, I have 2 tablespublic class User{ public int Id { get; set; } public string Name { get; set; } public string Password { get; set; } public virtual Organization Organization { get; set; }} public class Organization { public int Id { get; set; } public string Name { get; set; } public string EmailAddress { get; set; } public string Password { get; set; } public override bool Equals(object obj) { Organization that = obj as Organization; if (that != null) { return (this.Id == that.Id); } return base.Equals(obj); } } 尝试向用户插入行时出现以下错误。While trying to insert row into User I get following error.Cannot insert explicit value for identity column in table 'Organizations' when IDENTITY_INSERT is set to OFF. 代码如下Code is as following[HttpPost] public async Task<IActionResult> Post([FromBody]User p_User) { try { using (var dataContext = new AspCoreContext(AspCoreContext.BuildOptions())) { dataContext.Users.Add(p_User); await dataContext.SaveChangesAsync(); return Ok(p_User); } } catch (Exception ex) { const string msg = "Unable to insert user"; Globals.ErrorLogger(ex, msg); return StatusCode((int)HttpStatusCode.InternalServerError, msg); } } 请求正文是While request body is{ "name": "Qadeer", "password": "123456", "token": null, "organization": {"Id": "1"}} 我尝试了什么: 尝试设置关系表示法What I have tried:tried settings relational notations推荐答案它说你试图插入IDENTITY列中的新值(生成自己的值)。 如果在Id上放置[Key]属性(即键)匹配IDENTITY列属性的字段,它可能会解决您的问题。It says you're trying to insert a new value into an IDENTITY column (which generates it own values).If you put a [Key] attribute on the "Id" (i.e. the "key" field that matches the IDENTITY column) property it will probably fix your problem. 这篇关于当IDENTITY_INSERT设置为OFF时,从实体框架核心获取错误“无法在表'组织'中为标识列插入显式值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-11 08:04