Can't insert same Entity (with different related properties-entity) to another Entity












0















I have an Entity Product who has a collection of Suppliers (which is also an Entity) and i have a Contract Entity who has a collection of Products. A contract can have multiple products, even 2 same products but with a different Supplier.



When i try to add this second product to my contract (same product but different Supplier this time) EF seems to ignore it and doesn't add it to the Contract.Products collection. No errors but it doens't add it. How can i bypass this behavior or setup my model/logic in a way that i can perform this action?



Code:



// THIS CONTEXT RESIDES IN A USING BLOCK
// THE updateContracts.Products ARE COMING FROM ANOTHER CONTEXT and we are receiving this entity as a parameter

// fetching the contract we are updating from database
Contract contractFromDB = ctx.Contracts.Include(s)(...)Where(p => p.ID == updateContract.ID).FirstOrDefault();

// list to populate the products we have added
List<Product> productsToAddToDBContract = new List<Product>();

foreach (Entity.Product product in updateContract.Products)
{
if (!contractFromDB.Products.Any(prod => prod.ProductName == product.ProductName))
{
// tried detaching it but didn't work
//ctx.Entry(product).State = EntityState.Detached;
productsToAddToDBContract.Add(product);
}
}

foreach (Product product in productsToAddToDBContract)
{
// get these from DB and add those to DB contract products
Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();
if (productToAdd != null)
{
// HERE IS WHERE EF DOESN'T ADD THE SECOND PRODUCT (WHICH IS THE SAME BUT FROM ANOTHER SUPPLIER)
contractFromDB.Products.Add(productToAdd);
}
}


Thank you very much.



EDIT:
I tried to remove the line where i fetched my product from Database



Product productToAdd = ctx.Products.Include(...).Where(...).FirstOrDefault();


and just use the product i already fetched before and passing with the updateContract.Products, i got "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."



so i went and attach the product from this iteration:



foreach (Product product in productsToAddToDBContract)
{
// removed this line:
// Entity.Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();

// and added this one
ctx.Products.Attach(product);
contractFromDB.Products.Add(product);
}


then i received '"Attaching an entity of type 'Supplier' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate." Note that the product already has a supplier attached/included to it but from another context (same as the product's context).



This has to regarding the relation of Product and Supplier i think, or maybe because i am using different contexts, i don't know but i will investigate further and post back.



Feel free to contribute in any way of course :)










share|improve this question

























  • please include you code: stackoverflow.com/help/mcve

    – Hooman Bahreini
    Nov 28 '18 at 8:57











  • @Hooman, i updated the original description and added some code. Let me know if i need to clarify anything else. Thank you.

    – Dimitri
    Nov 28 '18 at 9:22











  • have you added your code? :-)

    – Hooman Bahreini
    Nov 28 '18 at 9:26











  • oh my (didn't press the save button, silly me), updated ;)

    – Dimitri
    Nov 28 '18 at 9:40






  • 1





    have a look at this post, it might be helpful... it explains how to add a new Entity to your DbContext, or update the existing Entity, if it has already been added.

    – Hooman Bahreini
    Nov 28 '18 at 12:08


















0















I have an Entity Product who has a collection of Suppliers (which is also an Entity) and i have a Contract Entity who has a collection of Products. A contract can have multiple products, even 2 same products but with a different Supplier.



When i try to add this second product to my contract (same product but different Supplier this time) EF seems to ignore it and doesn't add it to the Contract.Products collection. No errors but it doens't add it. How can i bypass this behavior or setup my model/logic in a way that i can perform this action?



Code:



// THIS CONTEXT RESIDES IN A USING BLOCK
// THE updateContracts.Products ARE COMING FROM ANOTHER CONTEXT and we are receiving this entity as a parameter

// fetching the contract we are updating from database
Contract contractFromDB = ctx.Contracts.Include(s)(...)Where(p => p.ID == updateContract.ID).FirstOrDefault();

// list to populate the products we have added
List<Product> productsToAddToDBContract = new List<Product>();

foreach (Entity.Product product in updateContract.Products)
{
if (!contractFromDB.Products.Any(prod => prod.ProductName == product.ProductName))
{
// tried detaching it but didn't work
//ctx.Entry(product).State = EntityState.Detached;
productsToAddToDBContract.Add(product);
}
}

foreach (Product product in productsToAddToDBContract)
{
// get these from DB and add those to DB contract products
Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();
if (productToAdd != null)
{
// HERE IS WHERE EF DOESN'T ADD THE SECOND PRODUCT (WHICH IS THE SAME BUT FROM ANOTHER SUPPLIER)
contractFromDB.Products.Add(productToAdd);
}
}


Thank you very much.



EDIT:
I tried to remove the line where i fetched my product from Database



Product productToAdd = ctx.Products.Include(...).Where(...).FirstOrDefault();


and just use the product i already fetched before and passing with the updateContract.Products, i got "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."



so i went and attach the product from this iteration:



foreach (Product product in productsToAddToDBContract)
{
// removed this line:
// Entity.Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();

// and added this one
ctx.Products.Attach(product);
contractFromDB.Products.Add(product);
}


then i received '"Attaching an entity of type 'Supplier' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate." Note that the product already has a supplier attached/included to it but from another context (same as the product's context).



This has to regarding the relation of Product and Supplier i think, or maybe because i am using different contexts, i don't know but i will investigate further and post back.



Feel free to contribute in any way of course :)










share|improve this question

























  • please include you code: stackoverflow.com/help/mcve

    – Hooman Bahreini
    Nov 28 '18 at 8:57











  • @Hooman, i updated the original description and added some code. Let me know if i need to clarify anything else. Thank you.

    – Dimitri
    Nov 28 '18 at 9:22











  • have you added your code? :-)

    – Hooman Bahreini
    Nov 28 '18 at 9:26











  • oh my (didn't press the save button, silly me), updated ;)

    – Dimitri
    Nov 28 '18 at 9:40






  • 1





    have a look at this post, it might be helpful... it explains how to add a new Entity to your DbContext, or update the existing Entity, if it has already been added.

    – Hooman Bahreini
    Nov 28 '18 at 12:08
















0












0








0








I have an Entity Product who has a collection of Suppliers (which is also an Entity) and i have a Contract Entity who has a collection of Products. A contract can have multiple products, even 2 same products but with a different Supplier.



When i try to add this second product to my contract (same product but different Supplier this time) EF seems to ignore it and doesn't add it to the Contract.Products collection. No errors but it doens't add it. How can i bypass this behavior or setup my model/logic in a way that i can perform this action?



Code:



// THIS CONTEXT RESIDES IN A USING BLOCK
// THE updateContracts.Products ARE COMING FROM ANOTHER CONTEXT and we are receiving this entity as a parameter

// fetching the contract we are updating from database
Contract contractFromDB = ctx.Contracts.Include(s)(...)Where(p => p.ID == updateContract.ID).FirstOrDefault();

// list to populate the products we have added
List<Product> productsToAddToDBContract = new List<Product>();

foreach (Entity.Product product in updateContract.Products)
{
if (!contractFromDB.Products.Any(prod => prod.ProductName == product.ProductName))
{
// tried detaching it but didn't work
//ctx.Entry(product).State = EntityState.Detached;
productsToAddToDBContract.Add(product);
}
}

foreach (Product product in productsToAddToDBContract)
{
// get these from DB and add those to DB contract products
Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();
if (productToAdd != null)
{
// HERE IS WHERE EF DOESN'T ADD THE SECOND PRODUCT (WHICH IS THE SAME BUT FROM ANOTHER SUPPLIER)
contractFromDB.Products.Add(productToAdd);
}
}


Thank you very much.



EDIT:
I tried to remove the line where i fetched my product from Database



Product productToAdd = ctx.Products.Include(...).Where(...).FirstOrDefault();


and just use the product i already fetched before and passing with the updateContract.Products, i got "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."



so i went and attach the product from this iteration:



foreach (Product product in productsToAddToDBContract)
{
// removed this line:
// Entity.Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();

// and added this one
ctx.Products.Attach(product);
contractFromDB.Products.Add(product);
}


then i received '"Attaching an entity of type 'Supplier' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate." Note that the product already has a supplier attached/included to it but from another context (same as the product's context).



This has to regarding the relation of Product and Supplier i think, or maybe because i am using different contexts, i don't know but i will investigate further and post back.



Feel free to contribute in any way of course :)










share|improve this question
















I have an Entity Product who has a collection of Suppliers (which is also an Entity) and i have a Contract Entity who has a collection of Products. A contract can have multiple products, even 2 same products but with a different Supplier.



When i try to add this second product to my contract (same product but different Supplier this time) EF seems to ignore it and doesn't add it to the Contract.Products collection. No errors but it doens't add it. How can i bypass this behavior or setup my model/logic in a way that i can perform this action?



Code:



// THIS CONTEXT RESIDES IN A USING BLOCK
// THE updateContracts.Products ARE COMING FROM ANOTHER CONTEXT and we are receiving this entity as a parameter

// fetching the contract we are updating from database
Contract contractFromDB = ctx.Contracts.Include(s)(...)Where(p => p.ID == updateContract.ID).FirstOrDefault();

// list to populate the products we have added
List<Product> productsToAddToDBContract = new List<Product>();

foreach (Entity.Product product in updateContract.Products)
{
if (!contractFromDB.Products.Any(prod => prod.ProductName == product.ProductName))
{
// tried detaching it but didn't work
//ctx.Entry(product).State = EntityState.Detached;
productsToAddToDBContract.Add(product);
}
}

foreach (Product product in productsToAddToDBContract)
{
// get these from DB and add those to DB contract products
Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();
if (productToAdd != null)
{
// HERE IS WHERE EF DOESN'T ADD THE SECOND PRODUCT (WHICH IS THE SAME BUT FROM ANOTHER SUPPLIER)
contractFromDB.Products.Add(productToAdd);
}
}


Thank you very much.



EDIT:
I tried to remove the line where i fetched my product from Database



Product productToAdd = ctx.Products.Include(...).Where(...).FirstOrDefault();


and just use the product i already fetched before and passing with the updateContract.Products, i got "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."



so i went and attach the product from this iteration:



foreach (Product product in productsToAddToDBContract)
{
// removed this line:
// Entity.Product productToAdd = ctx.Products.Include(p=> p.Suppliers).Where(prod=> prod.ProductName == product.ProductName).FirstOrDefault();

// and added this one
ctx.Products.Attach(product);
contractFromDB.Products.Add(product);
}


then i received '"Attaching an entity of type 'Supplier' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate." Note that the product already has a supplier attached/included to it but from another context (same as the product's context).



This has to regarding the relation of Product and Supplier i think, or maybe because i am using different contexts, i don't know but i will investigate further and post back.



Feel free to contribute in any way of course :)







asp.net-mvc collections entity-framework-6 relational-database






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 10:46







Dimitri

















asked Nov 28 '18 at 8:29









DimitriDimitri

346514




346514













  • please include you code: stackoverflow.com/help/mcve

    – Hooman Bahreini
    Nov 28 '18 at 8:57











  • @Hooman, i updated the original description and added some code. Let me know if i need to clarify anything else. Thank you.

    – Dimitri
    Nov 28 '18 at 9:22











  • have you added your code? :-)

    – Hooman Bahreini
    Nov 28 '18 at 9:26











  • oh my (didn't press the save button, silly me), updated ;)

    – Dimitri
    Nov 28 '18 at 9:40






  • 1





    have a look at this post, it might be helpful... it explains how to add a new Entity to your DbContext, or update the existing Entity, if it has already been added.

    – Hooman Bahreini
    Nov 28 '18 at 12:08





















  • please include you code: stackoverflow.com/help/mcve

    – Hooman Bahreini
    Nov 28 '18 at 8:57











  • @Hooman, i updated the original description and added some code. Let me know if i need to clarify anything else. Thank you.

    – Dimitri
    Nov 28 '18 at 9:22











  • have you added your code? :-)

    – Hooman Bahreini
    Nov 28 '18 at 9:26











  • oh my (didn't press the save button, silly me), updated ;)

    – Dimitri
    Nov 28 '18 at 9:40






  • 1





    have a look at this post, it might be helpful... it explains how to add a new Entity to your DbContext, or update the existing Entity, if it has already been added.

    – Hooman Bahreini
    Nov 28 '18 at 12:08



















please include you code: stackoverflow.com/help/mcve

– Hooman Bahreini
Nov 28 '18 at 8:57





please include you code: stackoverflow.com/help/mcve

– Hooman Bahreini
Nov 28 '18 at 8:57













@Hooman, i updated the original description and added some code. Let me know if i need to clarify anything else. Thank you.

– Dimitri
Nov 28 '18 at 9:22





@Hooman, i updated the original description and added some code. Let me know if i need to clarify anything else. Thank you.

– Dimitri
Nov 28 '18 at 9:22













have you added your code? :-)

– Hooman Bahreini
Nov 28 '18 at 9:26





have you added your code? :-)

– Hooman Bahreini
Nov 28 '18 at 9:26













oh my (didn't press the save button, silly me), updated ;)

– Dimitri
Nov 28 '18 at 9:40





oh my (didn't press the save button, silly me), updated ;)

– Dimitri
Nov 28 '18 at 9:40




1




1





have a look at this post, it might be helpful... it explains how to add a new Entity to your DbContext, or update the existing Entity, if it has already been added.

– Hooman Bahreini
Nov 28 '18 at 12:08







have a look at this post, it might be helpful... it explains how to add a new Entity to your DbContext, or update the existing Entity, if it has already been added.

– Hooman Bahreini
Nov 28 '18 at 12:08














1 Answer
1






active

oldest

votes


















0














The issue was my model structure, i can't elaborate on how it was but the related entities relation was not setup correctly, i have created a new entity that holds a ProductId-SupplierId and others, tweaking it till i got what i wanted. The reason why i got these errors (stated above) was because i didn't attach all the related entities when performing actions, when i refered the proper related entities to my product, the errors went away... :)



Hope this helps someone and forgive me for the somewhat unclear solution, i am in the middle of this project and time is an issue, for know the company wants a working solution not a clean one so i didn't not everything down ...



Kind regards!






share|improve this answer























    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%2f53515118%2fcant-insert-same-entity-with-different-related-properties-entity-to-another-e%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The issue was my model structure, i can't elaborate on how it was but the related entities relation was not setup correctly, i have created a new entity that holds a ProductId-SupplierId and others, tweaking it till i got what i wanted. The reason why i got these errors (stated above) was because i didn't attach all the related entities when performing actions, when i refered the proper related entities to my product, the errors went away... :)



    Hope this helps someone and forgive me for the somewhat unclear solution, i am in the middle of this project and time is an issue, for know the company wants a working solution not a clean one so i didn't not everything down ...



    Kind regards!






    share|improve this answer




























      0














      The issue was my model structure, i can't elaborate on how it was but the related entities relation was not setup correctly, i have created a new entity that holds a ProductId-SupplierId and others, tweaking it till i got what i wanted. The reason why i got these errors (stated above) was because i didn't attach all the related entities when performing actions, when i refered the proper related entities to my product, the errors went away... :)



      Hope this helps someone and forgive me for the somewhat unclear solution, i am in the middle of this project and time is an issue, for know the company wants a working solution not a clean one so i didn't not everything down ...



      Kind regards!






      share|improve this answer


























        0












        0








        0







        The issue was my model structure, i can't elaborate on how it was but the related entities relation was not setup correctly, i have created a new entity that holds a ProductId-SupplierId and others, tweaking it till i got what i wanted. The reason why i got these errors (stated above) was because i didn't attach all the related entities when performing actions, when i refered the proper related entities to my product, the errors went away... :)



        Hope this helps someone and forgive me for the somewhat unclear solution, i am in the middle of this project and time is an issue, for know the company wants a working solution not a clean one so i didn't not everything down ...



        Kind regards!






        share|improve this answer













        The issue was my model structure, i can't elaborate on how it was but the related entities relation was not setup correctly, i have created a new entity that holds a ProductId-SupplierId and others, tweaking it till i got what i wanted. The reason why i got these errors (stated above) was because i didn't attach all the related entities when performing actions, when i refered the proper related entities to my product, the errors went away... :)



        Hope this helps someone and forgive me for the somewhat unclear solution, i am in the middle of this project and time is an issue, for know the company wants a working solution not a clean one so i didn't not everything down ...



        Kind regards!







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 3 '18 at 11:08









        DimitriDimitri

        346514




        346514
































            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%2f53515118%2fcant-insert-same-entity-with-different-related-properties-entity-to-another-e%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

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)