我想将一条新记录插入到我的 SQL 表中。我试过:
public void CreateComment(int questionId, string comment)
{
QuestionComment questionComment = context.TableName.Create();//1*
questionComment.propertyThatIsNotAConstraint= questionId;
questionComment.body = comment;
context.QuestionComments.Add(questionComment);
context.SaveChanges();//ERROR...
}
1* 我很惊讶地看到智能感知告诉我:“请注意,新实体未添加或附加到集合中”
错误读取:
“违反主键约束'PK_TableName'。无法插入
对象“dbo.TableName”中存在重复键。重复的键值是
(0)。\r\n该语句已终止。”
问题是questionComment
有它的PK:questionComment.Id
默认为0
。它需要是下一个可用的身份,否则不会填充并执行“正常”身份插入。
实体框架期望我如何处理这种情况?
按照要求:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Feedback.Models
{
using System;
using System.Collections.Generic;
public partial class QuestionComment
{
public int id { get; set; }
public int questionId { get; set; }
public string body { get; set; }
public int commentIndex { get; set; }
}
}
我通过以下方式修复了它:
转到 SQL 并确保表的“身份规范”>“是身份”> 设置为“是”。如果必须更改数据库,则更新 *.edmx 文件。
检查 *.edmx > 实体属性 > StoreGeneratePattern 的标识,确保其设置为Identity
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)