使用身份主键将新实体插入上下文 [英] Insert new entity to context with identity primary key

查看:89
本文介绍了使用身份主键将新实体插入上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的SQL表中插入一条新记录。我尝试过:

I want to insert a new record into my SQL table. I tried:

        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告诉我:请注意,新实体未添加或附加到集合中

1* I'm surprised to see intellisense tell me: "Note that the new entity is not added or attached to the set"

错误读取:


违反主键约束'PK_TableName'。无法在对象'dbo.TableName'中插入
个重复键。重复的键值为
(0)。\r\n该语句已终止。

"Violation of PRIMARY KEY constraint 'PK_TableName'. Cannot insert duplicate key in object 'dbo.TableName'. The duplicate key value is (0).\r\nThe statement has been terminated."

问题是 questionComment 有它的PK: questionComment.Id 默认为 0 。它必须是下一个可用的Identity或不填充,并进行常规身份插入。

The problem is that questionComment has its PK: questionComment.Id defaulted to 0. It needs to be the next available Identity or otherwise not populated and do a "normal" identity insert.

实体框架如何期望我处理此场景?

How does entity framework expect me to handle this scenerio?

根据要求:

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


推荐答案

我通过以下方式修复它:

I fixed it by:


  1. 转到SQL并确保表具有 Identity Specification> Is Identity> set对。如果必须更改数据库,则更新* .edmx文件。

  1. Go to SQL and make sure to the Table has the "Identity Specification" > Is Identity > set to Yes. Then update the *.edmx file if you had to make a DB change.

检查* .edmx>实体属性> StoreGeneratedPattern以确保身份,以确保它设置为身份

Check the *.edmx > Entity properties > StoreGeneratedPattern for the identity to ensure that it is set to Identity

这篇关于使用身份主键将新实体插入上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆