P.B*_*key 20 c# entity-framework
我想在我的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...
}
Run Code Online (Sandbox Code Playgroud)
1*我很惊讶地看到intellisense告诉我: "请注意,新实体未添加或附加到集合中"
错误读取:
"违反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; }
}
}
Run Code Online (Sandbox Code Playgroud)
P.B*_*key 35
我通过以下方式修复:
转到SQL并确保表中的"Identity Specification"> Is Identity>设置为Yes.如果必须更改数据库,则更新*.edmx文件.
检查*.edmx>实体属性> StoreGeneratedPattern以获取标识,以确保将其设置为Identity

| 归档时间: |
|
| 查看次数: |
27536 次 |
| 最近记录: |