C# 使用标识主键向上下文插入新实体
我想在我的SQL表中插入一条新记录。我试过:C# 使用标识主键向上下文插入新实体,c#,entity-framework,C#,Entity Framework,我想在我的SQL表中插入一条新记录。我试过: public void CreateComment(int questionId, string comment) { QuestionComment questionComment = context.TableName.Create();//1* questionComment.propertyThatIsNotAConstraint= questionId;
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*我惊讶地看到intellisense告诉我:“请注意,新实体未添加或附加到集合”
错误内容如下:
违反主键约束“PK_TableName”。无法插入
对象“dbo.TableName”中存在重复的键。重复的键值为
(0)。\r\n语句已终止
问题是questionComment
的主键: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; }
}
}
//------------------------------------------------------------------------------
//
//此代码是从模板生成的。
//
//手动更改此文件可能会导致应用程序出现意外行为。
//如果重新生成代码,将覆盖对此文件的手动更改。
//
//------------------------------------------------------------------------------
名称空间反馈.模型
{
使用制度;
使用System.Collections.Generic;
公共部分类问题注释
{
公共int id{get;set;}
public int questionId{get;set;}
公共字符串体{get;set;}
public int commentIndex{get;set;}
}
}
EF文档指出,当为配置了propConfig.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
换句话说。EF在插入数据库时不关心newCommentObject.Id的值是多少。相反,它将允许数据库生成下一个标识值。我通过以下方法修复了它:
调用
SaveChanges()
后,newCommentObject.questionId
将包含数据库新生成的密钥。@haim770-我用收到的确切错误和错误位置更新了问题。如果有某种机制或顺序可以解决这个问题,请给出答案。我通常会这样做:数据库中我的标识从1开始;我在C#中的新实体从-1向下获得“伪”PK值-当实际插入到表中时,这些PK值将被替换(但是使用单独的、不同的“伪”PK值确保可以很好地处理实体,甚至从其他实体引用它们!)您使用的映射类型是什么?请发布映射代码以及QuestionComment
类。另外,您试图通过使用context.TableName.Create()
创建实体来实现什么?不清楚您实际添加的实体类型是TableName
还是QuestionComment
?我不确定如何将此应用于我的情况。我对这房子不熟悉。你能说明这是如何适用于我的问题的吗?换句话说,就是演示如何修复错误的代码。假设您设置了QuestionComments表。如果使用EF的fluent api,它可能看起来像modelBuilder.Entity().HasKey(c=>/**/)代码>。您可以将设置设置为modelBuilder.Entity().HasKey(c=>c.Id/*如果Id是表的主键*/)
或tomodelBuilder.Entity().HasKey(c=>/**/).Property(c=>c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
我可能会建议将QuestionComments上的Id设置为表的主键,因为这听起来像是。老兄,我也犯了同样的错误,但我没有意识到我没有创建标识列。谢谢(是的,我知道,“谢谢”的评论是不受欢迎的)更新.edmx文件对我不起作用。我不得不从.edmx中删除该表并重新添加它。