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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page

            Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices