Microsoft Entity Framework Core: Cannot insert duplicate key in object The 2019 Stack Overflow Developer Survey Results Are InInsert, on duplicate update in PostgreSQL?How can I get Id of inserted entity in Entity framework?Entity Framework Code First - Cannot insert duplicate key in object 'db'Fastest Way of Inserting in Entity FrameworkEntity Framework 5 Updating a RecordEntity Framework Cannot insert duplicate key in objectcannot insert duplicate key in object exception efEntity Framework - “cannot insert duplicate object” for child modelHandle duplicate key violations in EntityFramework CoreViolation of PRIMARY KEY constraint 'PK_StudentCourses'. Cannot insert duplicate key

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

Output the Arecibo Message

Loose spokes after only a few rides

Why are there uneven bright areas in this photo of black hole?

Match Roman Numerals

Why doesn't shell automatically fix "useless use of cat"?

How much of the clove should I use when using big garlic heads?

What do I do when my TA workload is more than expected?

What is this sharp, curved notch on my knife for?

Can an undergraduate be advised by a professor who is very far away?

The difference between dialogue marks

Short story: child made less intelligent and less attractive

Keeping a retro style to sci-fi spaceships?

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

How to translate "being like"?

What is preventing me from simply constructing a hash that's lower than the current target?

Mathematics of imaging the black hole

What is the motivation for a law requiring 2 parties to consent for recording a conversation

What is the meaning of Triage in Cybersec world?

How do PCB vias affect signal quality?

How do you keep chess fun when your opponent constantly beats you?

How can I define good in a religion that claims no moral authority?

For what reasons would an animal species NOT cross a *horizontal* land bridge?

Why not take a picture of a closer black hole?



Microsoft Entity Framework Core: Cannot insert duplicate key in object



The 2019 Stack Overflow Developer Survey Results Are InInsert, on duplicate update in PostgreSQL?How can I get Id of inserted entity in Entity framework?Entity Framework Code First - Cannot insert duplicate key in object 'db'Fastest Way of Inserting in Entity FrameworkEntity Framework 5 Updating a RecordEntity Framework Cannot insert duplicate key in objectcannot insert duplicate key in object exception efEntity Framework - “cannot insert duplicate object” for child modelHandle duplicate key violations in EntityFramework CoreViolation of PRIMARY KEY constraint 'PK_StudentCourses'. Cannot insert duplicate key



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am trying to update a parent entity, GuildMemberTeam, with child entities, GuildMember, Team and GuildMemberChallenge which also has a child entities, GuildMember and Challenge but am getting the following inner exception:




Inner Exception 1: SqlException: Violation of PRIMARY KEY constraint
'PK_Challenge'. Cannot insert duplicate key in object 'dbo.Challenge'.
The duplicate key value is (15ae8798-8567-457b-812a-5820cf7843e5). The
statement has been terminated.




The only new entity is the GuildMemberTeam as all the others already exist, but these are checked and recreated as follows:



public void AddChallenge(Challenge challenge)

if (challenge != null)

var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;

Challenge = new Challenge(id, challenge.Name, challenge.Phase, challenge.Type, challenge.Star, challenge.Gear, challenge.Level, challenge.Reward);




This works for all the other entities apart from Challenge where i get the error. Can anyone please help me understand what i am doing wrong.










share|improve this question
























  • You are trying to insert a new row with an ID that is already present in the database. default(Guid) ? Guid.NewGuid() : challenge.Id; <-- here you are using the existing challenge ID if it is not equal to the default(Guid)

    – Kristóf Tóth
    Mar 8 at 11:15












  • Kristof - I know i am doing that but i am doing this on all the other entities and it is fine, just on this child-child entity

    – mat_e3
    Mar 8 at 11:41

















0















I am trying to update a parent entity, GuildMemberTeam, with child entities, GuildMember, Team and GuildMemberChallenge which also has a child entities, GuildMember and Challenge but am getting the following inner exception:




Inner Exception 1: SqlException: Violation of PRIMARY KEY constraint
'PK_Challenge'. Cannot insert duplicate key in object 'dbo.Challenge'.
The duplicate key value is (15ae8798-8567-457b-812a-5820cf7843e5). The
statement has been terminated.




The only new entity is the GuildMemberTeam as all the others already exist, but these are checked and recreated as follows:



public void AddChallenge(Challenge challenge)

if (challenge != null)

var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;

Challenge = new Challenge(id, challenge.Name, challenge.Phase, challenge.Type, challenge.Star, challenge.Gear, challenge.Level, challenge.Reward);




This works for all the other entities apart from Challenge where i get the error. Can anyone please help me understand what i am doing wrong.










share|improve this question
























  • You are trying to insert a new row with an ID that is already present in the database. default(Guid) ? Guid.NewGuid() : challenge.Id; <-- here you are using the existing challenge ID if it is not equal to the default(Guid)

    – Kristóf Tóth
    Mar 8 at 11:15












  • Kristof - I know i am doing that but i am doing this on all the other entities and it is fine, just on this child-child entity

    – mat_e3
    Mar 8 at 11:41













0












0








0








I am trying to update a parent entity, GuildMemberTeam, with child entities, GuildMember, Team and GuildMemberChallenge which also has a child entities, GuildMember and Challenge but am getting the following inner exception:




Inner Exception 1: SqlException: Violation of PRIMARY KEY constraint
'PK_Challenge'. Cannot insert duplicate key in object 'dbo.Challenge'.
The duplicate key value is (15ae8798-8567-457b-812a-5820cf7843e5). The
statement has been terminated.




The only new entity is the GuildMemberTeam as all the others already exist, but these are checked and recreated as follows:



public void AddChallenge(Challenge challenge)

if (challenge != null)

var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;

Challenge = new Challenge(id, challenge.Name, challenge.Phase, challenge.Type, challenge.Star, challenge.Gear, challenge.Level, challenge.Reward);




This works for all the other entities apart from Challenge where i get the error. Can anyone please help me understand what i am doing wrong.










share|improve this question
















I am trying to update a parent entity, GuildMemberTeam, with child entities, GuildMember, Team and GuildMemberChallenge which also has a child entities, GuildMember and Challenge but am getting the following inner exception:




Inner Exception 1: SqlException: Violation of PRIMARY KEY constraint
'PK_Challenge'. Cannot insert duplicate key in object 'dbo.Challenge'.
The duplicate key value is (15ae8798-8567-457b-812a-5820cf7843e5). The
statement has been terminated.




The only new entity is the GuildMemberTeam as all the others already exist, but these are checked and recreated as follows:



public void AddChallenge(Challenge challenge)

if (challenge != null)

var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;

Challenge = new Challenge(id, challenge.Name, challenge.Phase, challenge.Type, challenge.Star, challenge.Gear, challenge.Level, challenge.Reward);




This works for all the other entities apart from Challenge where i get the error. Can anyone please help me understand what i am doing wrong.







c# sql entity-framework-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 11:46









Dave

2,92281830




2,92281830










asked Mar 8 at 11:11









mat_e3mat_e3

266




266












  • You are trying to insert a new row with an ID that is already present in the database. default(Guid) ? Guid.NewGuid() : challenge.Id; <-- here you are using the existing challenge ID if it is not equal to the default(Guid)

    – Kristóf Tóth
    Mar 8 at 11:15












  • Kristof - I know i am doing that but i am doing this on all the other entities and it is fine, just on this child-child entity

    – mat_e3
    Mar 8 at 11:41

















  • You are trying to insert a new row with an ID that is already present in the database. default(Guid) ? Guid.NewGuid() : challenge.Id; <-- here you are using the existing challenge ID if it is not equal to the default(Guid)

    – Kristóf Tóth
    Mar 8 at 11:15












  • Kristof - I know i am doing that but i am doing this on all the other entities and it is fine, just on this child-child entity

    – mat_e3
    Mar 8 at 11:41
















You are trying to insert a new row with an ID that is already present in the database. default(Guid) ? Guid.NewGuid() : challenge.Id; <-- here you are using the existing challenge ID if it is not equal to the default(Guid)

– Kristóf Tóth
Mar 8 at 11:15






You are trying to insert a new row with an ID that is already present in the database. default(Guid) ? Guid.NewGuid() : challenge.Id; <-- here you are using the existing challenge ID if it is not equal to the default(Guid)

– Kristóf Tóth
Mar 8 at 11:15














Kristof - I know i am doing that but i am doing this on all the other entities and it is fine, just on this child-child entity

– mat_e3
Mar 8 at 11:41





Kristof - I know i am doing that but i am doing this on all the other entities and it is fine, just on this child-child entity

– mat_e3
Mar 8 at 11:41












2 Answers
2






active

oldest

votes


















0














It doesn't change the fact that the problem is that you are trying to insert the same row twice (same Guid=Id) into the dbo.Challenge table.



  1. This might be due to a debugging issue or something. You can either delete the row from the table with a
    DELETE FROM [Challenge] WHERE Id = '15ae8798-8567-457b-812a-5820cf7843e5' and try running the app again.


  2. If this doesn't solve your problem your entity management is faulty and you have to revise the ID handling. Implement ID checking before you try to save your context or something like that.


The other issue might be that your classes are not defined properly and EF doesn't recognize the relations. The relationships you are talking about are not parent-child, they are either one-to-many, many-to-many, many-to-one or none. DB RELATIONS



Each of your POCO-s should contain and instance of the other class, thus you define a relationship. E.g. if your GuildMemberChallenge contains an IEnumerable and a property with type of challenge.



If none of the above are a solution I need some more code (your classes, the repository) to figure it out.



Update:
When you are adding a new GuildMemberChallenge, which I assume you are trying to do now. You should set it's Challenge property to an existing entity if it exists, if it doesn't you can create one, but at the moment you are trying to create a Challenge that already exists in the database.






share|improve this answer






























    0














    You are creating new Challenge but pass id of existing Challenge if it is set.



    var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;


    I think you, that if you create new entity you should always create new Id



    var id = Guid.NewGuid();





    share|improve this answer























    • I don't want the Challenge entity to change though, it is just a child entity

      – mat_e3
      Mar 8 at 11:42











    • Why do you creating completely new Challenge then?

      – Pablo notPicasso
      Mar 8 at 11:48











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062004%2fmicrosoft-entity-framework-core-cannot-insert-duplicate-key-in-object%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    It doesn't change the fact that the problem is that you are trying to insert the same row twice (same Guid=Id) into the dbo.Challenge table.



    1. This might be due to a debugging issue or something. You can either delete the row from the table with a
      DELETE FROM [Challenge] WHERE Id = '15ae8798-8567-457b-812a-5820cf7843e5' and try running the app again.


    2. If this doesn't solve your problem your entity management is faulty and you have to revise the ID handling. Implement ID checking before you try to save your context or something like that.


    The other issue might be that your classes are not defined properly and EF doesn't recognize the relations. The relationships you are talking about are not parent-child, they are either one-to-many, many-to-many, many-to-one or none. DB RELATIONS



    Each of your POCO-s should contain and instance of the other class, thus you define a relationship. E.g. if your GuildMemberChallenge contains an IEnumerable and a property with type of challenge.



    If none of the above are a solution I need some more code (your classes, the repository) to figure it out.



    Update:
    When you are adding a new GuildMemberChallenge, which I assume you are trying to do now. You should set it's Challenge property to an existing entity if it exists, if it doesn't you can create one, but at the moment you are trying to create a Challenge that already exists in the database.






    share|improve this answer



























      0














      It doesn't change the fact that the problem is that you are trying to insert the same row twice (same Guid=Id) into the dbo.Challenge table.



      1. This might be due to a debugging issue or something. You can either delete the row from the table with a
        DELETE FROM [Challenge] WHERE Id = '15ae8798-8567-457b-812a-5820cf7843e5' and try running the app again.


      2. If this doesn't solve your problem your entity management is faulty and you have to revise the ID handling. Implement ID checking before you try to save your context or something like that.


      The other issue might be that your classes are not defined properly and EF doesn't recognize the relations. The relationships you are talking about are not parent-child, they are either one-to-many, many-to-many, many-to-one or none. DB RELATIONS



      Each of your POCO-s should contain and instance of the other class, thus you define a relationship. E.g. if your GuildMemberChallenge contains an IEnumerable and a property with type of challenge.



      If none of the above are a solution I need some more code (your classes, the repository) to figure it out.



      Update:
      When you are adding a new GuildMemberChallenge, which I assume you are trying to do now. You should set it's Challenge property to an existing entity if it exists, if it doesn't you can create one, but at the moment you are trying to create a Challenge that already exists in the database.






      share|improve this answer

























        0












        0








        0







        It doesn't change the fact that the problem is that you are trying to insert the same row twice (same Guid=Id) into the dbo.Challenge table.



        1. This might be due to a debugging issue or something. You can either delete the row from the table with a
          DELETE FROM [Challenge] WHERE Id = '15ae8798-8567-457b-812a-5820cf7843e5' and try running the app again.


        2. If this doesn't solve your problem your entity management is faulty and you have to revise the ID handling. Implement ID checking before you try to save your context or something like that.


        The other issue might be that your classes are not defined properly and EF doesn't recognize the relations. The relationships you are talking about are not parent-child, they are either one-to-many, many-to-many, many-to-one or none. DB RELATIONS



        Each of your POCO-s should contain and instance of the other class, thus you define a relationship. E.g. if your GuildMemberChallenge contains an IEnumerable and a property with type of challenge.



        If none of the above are a solution I need some more code (your classes, the repository) to figure it out.



        Update:
        When you are adding a new GuildMemberChallenge, which I assume you are trying to do now. You should set it's Challenge property to an existing entity if it exists, if it doesn't you can create one, but at the moment you are trying to create a Challenge that already exists in the database.






        share|improve this answer













        It doesn't change the fact that the problem is that you are trying to insert the same row twice (same Guid=Id) into the dbo.Challenge table.



        1. This might be due to a debugging issue or something. You can either delete the row from the table with a
          DELETE FROM [Challenge] WHERE Id = '15ae8798-8567-457b-812a-5820cf7843e5' and try running the app again.


        2. If this doesn't solve your problem your entity management is faulty and you have to revise the ID handling. Implement ID checking before you try to save your context or something like that.


        The other issue might be that your classes are not defined properly and EF doesn't recognize the relations. The relationships you are talking about are not parent-child, they are either one-to-many, many-to-many, many-to-one or none. DB RELATIONS



        Each of your POCO-s should contain and instance of the other class, thus you define a relationship. E.g. if your GuildMemberChallenge contains an IEnumerable and a property with type of challenge.



        If none of the above are a solution I need some more code (your classes, the repository) to figure it out.



        Update:
        When you are adding a new GuildMemberChallenge, which I assume you are trying to do now. You should set it's Challenge property to an existing entity if it exists, if it doesn't you can create one, but at the moment you are trying to create a Challenge that already exists in the database.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 12:50









        Kristóf TóthKristóf Tóth

        520314




        520314























            0














            You are creating new Challenge but pass id of existing Challenge if it is set.



            var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;


            I think you, that if you create new entity you should always create new Id



            var id = Guid.NewGuid();





            share|improve this answer























            • I don't want the Challenge entity to change though, it is just a child entity

              – mat_e3
              Mar 8 at 11:42











            • Why do you creating completely new Challenge then?

              – Pablo notPicasso
              Mar 8 at 11:48















            0














            You are creating new Challenge but pass id of existing Challenge if it is set.



            var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;


            I think you, that if you create new entity you should always create new Id



            var id = Guid.NewGuid();





            share|improve this answer























            • I don't want the Challenge entity to change though, it is just a child entity

              – mat_e3
              Mar 8 at 11:42











            • Why do you creating completely new Challenge then?

              – Pablo notPicasso
              Mar 8 at 11:48













            0












            0








            0







            You are creating new Challenge but pass id of existing Challenge if it is set.



            var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;


            I think you, that if you create new entity you should always create new Id



            var id = Guid.NewGuid();





            share|improve this answer













            You are creating new Challenge but pass id of existing Challenge if it is set.



            var id = challenge.Id == default(Guid) ? Guid.NewGuid() : challenge.Id;


            I think you, that if you create new entity you should always create new Id



            var id = Guid.NewGuid();






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 8 at 11:29









            Pablo notPicassoPablo notPicasso

            2,30331320




            2,30331320












            • I don't want the Challenge entity to change though, it is just a child entity

              – mat_e3
              Mar 8 at 11:42











            • Why do you creating completely new Challenge then?

              – Pablo notPicasso
              Mar 8 at 11:48

















            • I don't want the Challenge entity to change though, it is just a child entity

              – mat_e3
              Mar 8 at 11:42











            • Why do you creating completely new Challenge then?

              – Pablo notPicasso
              Mar 8 at 11:48
















            I don't want the Challenge entity to change though, it is just a child entity

            – mat_e3
            Mar 8 at 11:42





            I don't want the Challenge entity to change though, it is just a child entity

            – mat_e3
            Mar 8 at 11:42













            Why do you creating completely new Challenge then?

            – Pablo notPicasso
            Mar 8 at 11:48





            Why do you creating completely new Challenge then?

            – Pablo notPicasso
            Mar 8 at 11:48

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062004%2fmicrosoft-entity-framework-core-cannot-insert-duplicate-key-in-object%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved