Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert new entity to context with identity primary key

Tags:

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

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

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?

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; }
        }
    }
like image 855
P.Brian.Mackey Avatar asked Apr 29 '13 19:04

P.Brian.Mackey


People also ask

How do I set primary key in entity Framework?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

How does DbContext change state of entity?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.


2 Answers

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

enter image description here

like image 168
P.Brian.Mackey Avatar answered Oct 04 '22 05:10

P.Brian.Mackey


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

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

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

like image 22
Steven Wexler Avatar answered Oct 04 '22 03:10

Steven Wexler