Microsoft Entity Framework Core: Cannot insert duplicate key in objectInsert, 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

How did Doctor Strange see the winning outcome in Avengers: Infinity War?

How to write papers efficiently when English isn't my first language?

Lay out the Carpet

Do the temporary hit points from Reckless Abandon stack if I make multiple attacks on my turn?

Is a stroke of luck acceptable after a series of unfavorable events?

Proof of work - lottery approach

What is the difference between "behavior" and "behaviour"?

Detecting if an element is found inside a container

How to be diplomatic in refusing to write code that breaches the privacy of our users

Are student evaluations of teaching assistants read by others in the faculty?

Anatomically Correct Strange Women In Ponds Distributing Swords

How does Loki do this?

Large drywall patch supports

Why escape if the_content isnt?

Avoiding estate tax by giving multiple gifts

Purchasing a ticket for someone else in another country?

Method to test if a number is a perfect power?

Is this apparent Class Action settlement a spam message?

What is the opposite of 'gravitas'?

Would a high gravity rocky planet be guaranteed to have an atmosphere?

Where does the Z80 processor start executing from?

Why not increase contact surface when reentering the atmosphere?

Two monoidal structures and copowering

How to pronounce the slash sign



Microsoft Entity Framework Core: Cannot insert duplicate key in object


Insert, 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













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,84681830




2,84681830










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

            How to get text form Clipboard with JavaScript in Firefox 56?How to validate an email address in JavaScript?How do JavaScript closures work?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I copy to the clipboard in JavaScript?How do I include a JavaScript file in another JavaScript file?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            List of MPs elected to the English parliament in 1640 (April) Contents List of constituencies and members See also Notes References Navigation menueNational Archives – The Glynde Place ArchivesCobbett's Parliamentary history of England, from the Norman Conquest in 1066 to the year 1803'Aldermen in Parliament', The Aldermen of the City of London: Temp. Henry III – 1912onepage&q&f&#61, false 229