我想在我的 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* 我很惊讶地看到智能感知告诉我: “请注意,新实体没有添加或附加到集合中”
错误读取:
“违反 PRIMARY KEY 约束 '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; }
}
}