C# 使用身份主键将新实体插入上下文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16286309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:39:10  来源:igfitidea点击:

Insert new entity to context with identity primary key

c#entity-framework

提问by P.Brian.Mackey

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

我想在我的 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* I'm surprised to see intellisense tell me: "Note that the new entity is not added or attached to the set"

1* 我很惊讶地看到智能感知告诉我: “请注意,新实体没有添加或附加到集合中”

Error Reads:

错误读取:

"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."

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

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

问题是questionComment它的 PK:questionComment.Id默认为0. 它需要是下一个可用的身份或以其他方式未填充并执行“正常”身份插入。

How does entity framework expect me to handle this scenerio?

实体框架希望我如何处理这个场景?

As Requested:

按照要求:

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

采纳答案by P.Brian.Mackey

I fixed it by:

我通过以下方式修复它:

  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.

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

  1. 转到 SQL 并确保表具有“身份规范”> 是身份 > 设置为是。如果必须更改数据库,则更新 *.edmx 文件。

  2. 检查 *.edmx > Entity properties > StoreGeneratedPattern 以获取标识以确保将其设置为Identity

enter image description here

在此处输入图片说明

回答by Steven Wexler

EF documentation states that the database generates a value when a row is inserted for columns configured with propConfig.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)

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

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

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

In other words. EF won't care what value newCommentObject.Idis when inserting into the database. Instead, it'll allow the database to generate the next identity value.

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