使用标识主键将新实体插入上下文

时间:2013-04-29 19:06:59

标签: 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...
        }

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; }
        }
    }

2 个答案:

答案 0 :(得分:35)

我修理了:

  1. 转到SQL并确保表中包含&​​#34; Identity Specification&#34; &GT;是身份&gt;设为是。如果必须更改数据库,请更新* .edmx文件。

  2. 检查* .edmx&gt;实体属性&gt; StoreGeneratedPattern用于标识以确保将其设置为标识

  3. enter image description here

答案 1 :(得分:4)

EF文档指出数据库为为propConfig.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)配置的列插入行时生成值

http://msdn.microsoft.com/en-us/library/hh829109(v=vs.103).aspx

换句话说。插入数据库时​​,EF不关心newCommentObject.Id的值。相反,它将允许数据库生成下一个标识值。

相关问题