Entity Framework Core - Cannot insert explicit value when saving to another table












0














I'm trying to create an 'Order' object that has a Collection of 'OrderItem's that hold a 'Hamper' object. Basically, whenever I try to save the 'Order' object to my database, i keep getting this error that I can't insert explict values into the table for my hampers, except i'm not altering the Hamper data, i'm simply using those objects within another object.
My hamper model has :



[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]


Before the primary key object. I have no idea what to do to be perfectly honest and nothing i've found online has seemed to help. Whether i'm explicity adding the 'OrderItem' object one by one or the whole collection within the 'Order' object, I still can't get away from this error. I have linked the HamperID within the 'OrderItem' as a foriegn key, and i haven't had this issue when saving objects within other objects, it's just this example.
Anyway, here's the error. I wouldn't expect including the models would be much help, but the specific error is a follows:



Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table
'TblHamper' when IDENTITY_INSERT is set to OFF.


And here is the 'OrderItem' model that is causing the error whenever I try to save:



    [Key]
public int Id { get; set; }
public Hamper Hamper { get; set; }
public int Quantity { get; set; }
[ForeignKey("HamperID")]
public int HamperID { get; set; }









share|improve this question
























  • It sounds like the Hamper item isn't populated in your model structure before you try the insert. That would probably mean EF tries to generate a new insert for it when you add your OrderItem. I'd double check your model structure is fully populated with the references linked before you do the insert. See here: stackoverflow.com/questions/45300982/… - hope that is of some help
    – scgough
    Nov 23 at 9:10










  • The hamper is already saved in the database, i'm just creating a link between them. It's the same thing i've done with other objects so that's why i'm really confused as to why it's not working here.
    – Hendo16
    Nov 23 at 10:14










  • Sorry I mean if your object has a link to an existing Hamper then the data for that should be populated when you save the OrderItem otherwise EF will think it has to create a new entry for Hamper. It sounds like that is covered though and this is something else.
    – scgough
    Nov 23 at 10:26










  • TblHamper has no Primary Key or Identity is off. So it can't create the primary key when you insert. You need to check if it got scaffold-ed correctly when you initially created and then updated that table with EF. It appears it doesn't have key generator in place. Check it via right click design view in VS on that table. IF IDENTITY is missing you will need either recreate table or try to get it re-enabled.
    – mvermef
    Nov 26 at 3:04


















0














I'm trying to create an 'Order' object that has a Collection of 'OrderItem's that hold a 'Hamper' object. Basically, whenever I try to save the 'Order' object to my database, i keep getting this error that I can't insert explict values into the table for my hampers, except i'm not altering the Hamper data, i'm simply using those objects within another object.
My hamper model has :



[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]


Before the primary key object. I have no idea what to do to be perfectly honest and nothing i've found online has seemed to help. Whether i'm explicity adding the 'OrderItem' object one by one or the whole collection within the 'Order' object, I still can't get away from this error. I have linked the HamperID within the 'OrderItem' as a foriegn key, and i haven't had this issue when saving objects within other objects, it's just this example.
Anyway, here's the error. I wouldn't expect including the models would be much help, but the specific error is a follows:



Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table
'TblHamper' when IDENTITY_INSERT is set to OFF.


And here is the 'OrderItem' model that is causing the error whenever I try to save:



    [Key]
public int Id { get; set; }
public Hamper Hamper { get; set; }
public int Quantity { get; set; }
[ForeignKey("HamperID")]
public int HamperID { get; set; }









share|improve this question
























  • It sounds like the Hamper item isn't populated in your model structure before you try the insert. That would probably mean EF tries to generate a new insert for it when you add your OrderItem. I'd double check your model structure is fully populated with the references linked before you do the insert. See here: stackoverflow.com/questions/45300982/… - hope that is of some help
    – scgough
    Nov 23 at 9:10










  • The hamper is already saved in the database, i'm just creating a link between them. It's the same thing i've done with other objects so that's why i'm really confused as to why it's not working here.
    – Hendo16
    Nov 23 at 10:14










  • Sorry I mean if your object has a link to an existing Hamper then the data for that should be populated when you save the OrderItem otherwise EF will think it has to create a new entry for Hamper. It sounds like that is covered though and this is something else.
    – scgough
    Nov 23 at 10:26










  • TblHamper has no Primary Key or Identity is off. So it can't create the primary key when you insert. You need to check if it got scaffold-ed correctly when you initially created and then updated that table with EF. It appears it doesn't have key generator in place. Check it via right click design view in VS on that table. IF IDENTITY is missing you will need either recreate table or try to get it re-enabled.
    – mvermef
    Nov 26 at 3:04
















0












0








0







I'm trying to create an 'Order' object that has a Collection of 'OrderItem's that hold a 'Hamper' object. Basically, whenever I try to save the 'Order' object to my database, i keep getting this error that I can't insert explict values into the table for my hampers, except i'm not altering the Hamper data, i'm simply using those objects within another object.
My hamper model has :



[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]


Before the primary key object. I have no idea what to do to be perfectly honest and nothing i've found online has seemed to help. Whether i'm explicity adding the 'OrderItem' object one by one or the whole collection within the 'Order' object, I still can't get away from this error. I have linked the HamperID within the 'OrderItem' as a foriegn key, and i haven't had this issue when saving objects within other objects, it's just this example.
Anyway, here's the error. I wouldn't expect including the models would be much help, but the specific error is a follows:



Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table
'TblHamper' when IDENTITY_INSERT is set to OFF.


And here is the 'OrderItem' model that is causing the error whenever I try to save:



    [Key]
public int Id { get; set; }
public Hamper Hamper { get; set; }
public int Quantity { get; set; }
[ForeignKey("HamperID")]
public int HamperID { get; set; }









share|improve this question















I'm trying to create an 'Order' object that has a Collection of 'OrderItem's that hold a 'Hamper' object. Basically, whenever I try to save the 'Order' object to my database, i keep getting this error that I can't insert explict values into the table for my hampers, except i'm not altering the Hamper data, i'm simply using those objects within another object.
My hamper model has :



[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]


Before the primary key object. I have no idea what to do to be perfectly honest and nothing i've found online has seemed to help. Whether i'm explicity adding the 'OrderItem' object one by one or the whole collection within the 'Order' object, I still can't get away from this error. I have linked the HamperID within the 'OrderItem' as a foriegn key, and i haven't had this issue when saving objects within other objects, it's just this example.
Anyway, here's the error. I wouldn't expect including the models would be much help, but the specific error is a follows:



Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table
'TblHamper' when IDENTITY_INSERT is set to OFF.


And here is the 'OrderItem' model that is causing the error whenever I try to save:



    [Key]
public int Id { get; set; }
public Hamper Hamper { get; set; }
public int Quantity { get; set; }
[ForeignKey("HamperID")]
public int HamperID { get; set; }






sql asp.net-core asp.net-core-mvc entity-framework-core sqlexception






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 at 9:20









Tetsuya Yamamoto

14.5k41939




14.5k41939










asked Nov 23 at 9:01









Hendo16

424




424












  • It sounds like the Hamper item isn't populated in your model structure before you try the insert. That would probably mean EF tries to generate a new insert for it when you add your OrderItem. I'd double check your model structure is fully populated with the references linked before you do the insert. See here: stackoverflow.com/questions/45300982/… - hope that is of some help
    – scgough
    Nov 23 at 9:10










  • The hamper is already saved in the database, i'm just creating a link between them. It's the same thing i've done with other objects so that's why i'm really confused as to why it's not working here.
    – Hendo16
    Nov 23 at 10:14










  • Sorry I mean if your object has a link to an existing Hamper then the data for that should be populated when you save the OrderItem otherwise EF will think it has to create a new entry for Hamper. It sounds like that is covered though and this is something else.
    – scgough
    Nov 23 at 10:26










  • TblHamper has no Primary Key or Identity is off. So it can't create the primary key when you insert. You need to check if it got scaffold-ed correctly when you initially created and then updated that table with EF. It appears it doesn't have key generator in place. Check it via right click design view in VS on that table. IF IDENTITY is missing you will need either recreate table or try to get it re-enabled.
    – mvermef
    Nov 26 at 3:04




















  • It sounds like the Hamper item isn't populated in your model structure before you try the insert. That would probably mean EF tries to generate a new insert for it when you add your OrderItem. I'd double check your model structure is fully populated with the references linked before you do the insert. See here: stackoverflow.com/questions/45300982/… - hope that is of some help
    – scgough
    Nov 23 at 9:10










  • The hamper is already saved in the database, i'm just creating a link between them. It's the same thing i've done with other objects so that's why i'm really confused as to why it's not working here.
    – Hendo16
    Nov 23 at 10:14










  • Sorry I mean if your object has a link to an existing Hamper then the data for that should be populated when you save the OrderItem otherwise EF will think it has to create a new entry for Hamper. It sounds like that is covered though and this is something else.
    – scgough
    Nov 23 at 10:26










  • TblHamper has no Primary Key or Identity is off. So it can't create the primary key when you insert. You need to check if it got scaffold-ed correctly when you initially created and then updated that table with EF. It appears it doesn't have key generator in place. Check it via right click design view in VS on that table. IF IDENTITY is missing you will need either recreate table or try to get it re-enabled.
    – mvermef
    Nov 26 at 3:04


















It sounds like the Hamper item isn't populated in your model structure before you try the insert. That would probably mean EF tries to generate a new insert for it when you add your OrderItem. I'd double check your model structure is fully populated with the references linked before you do the insert. See here: stackoverflow.com/questions/45300982/… - hope that is of some help
– scgough
Nov 23 at 9:10




It sounds like the Hamper item isn't populated in your model structure before you try the insert. That would probably mean EF tries to generate a new insert for it when you add your OrderItem. I'd double check your model structure is fully populated with the references linked before you do the insert. See here: stackoverflow.com/questions/45300982/… - hope that is of some help
– scgough
Nov 23 at 9:10












The hamper is already saved in the database, i'm just creating a link between them. It's the same thing i've done with other objects so that's why i'm really confused as to why it's not working here.
– Hendo16
Nov 23 at 10:14




The hamper is already saved in the database, i'm just creating a link between them. It's the same thing i've done with other objects so that's why i'm really confused as to why it's not working here.
– Hendo16
Nov 23 at 10:14












Sorry I mean if your object has a link to an existing Hamper then the data for that should be populated when you save the OrderItem otherwise EF will think it has to create a new entry for Hamper. It sounds like that is covered though and this is something else.
– scgough
Nov 23 at 10:26




Sorry I mean if your object has a link to an existing Hamper then the data for that should be populated when you save the OrderItem otherwise EF will think it has to create a new entry for Hamper. It sounds like that is covered though and this is something else.
– scgough
Nov 23 at 10:26












TblHamper has no Primary Key or Identity is off. So it can't create the primary key when you insert. You need to check if it got scaffold-ed correctly when you initially created and then updated that table with EF. It appears it doesn't have key generator in place. Check it via right click design view in VS on that table. IF IDENTITY is missing you will need either recreate table or try to get it re-enabled.
– mvermef
Nov 26 at 3:04






TblHamper has no Primary Key or Identity is off. So it can't create the primary key when you insert. You need to check if it got scaffold-ed correctly when you initially created and then updated that table with EF. It appears it doesn't have key generator in place. Check it via right click design view in VS on that table. IF IDENTITY is missing you will need either recreate table or try to get it re-enabled.
– mvermef
Nov 26 at 3:04














1 Answer
1






active

oldest

votes


















0














For EF Core to decide whether to update or create, it is controlled by Tracking. For your scenario, it seems you initialize a new Hamper when create a new Order with a new OrderItem.



Try options below:





  • Reset Hamper with Hamper in database.



            Hamper hamper = new Hamper { Id = 1, Name = "H1" };
    Hamper dbHamper = _context.Hamper.FirstOrDefault(h => h.Id == hamper.Id);
    OrderItem orderItem = new OrderItem { Title = "T1", HamperId = dbHamper.Id, Hamper = dbHamper };
    Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
    await _context.Order.AddAsync(order);
    await _context.SaveChangesAsync();



  • Attach to start Tracking



                Hamper hamper = new Hamper { Id = 1, Name = "H1" };
    _context.Attach(hamper);
    OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id, Hamper = hamper };
    Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
    await _context.Order.AddAsync(order);
    await _context.SaveChangesAsync();



  • Or, you could pass the HamperId without Hamper



                Hamper hamper = new Hamper { Id = 1, Name = "H1" };
    OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id };
    Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
    await _context.Order.AddAsync(order);
    await _context.SaveChangesAsync();







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%2f53443462%2fentity-framework-core-cannot-insert-explicit-value-when-saving-to-another-tabl%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














    For EF Core to decide whether to update or create, it is controlled by Tracking. For your scenario, it seems you initialize a new Hamper when create a new Order with a new OrderItem.



    Try options below:





    • Reset Hamper with Hamper in database.



              Hamper hamper = new Hamper { Id = 1, Name = "H1" };
      Hamper dbHamper = _context.Hamper.FirstOrDefault(h => h.Id == hamper.Id);
      OrderItem orderItem = new OrderItem { Title = "T1", HamperId = dbHamper.Id, Hamper = dbHamper };
      Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
      await _context.Order.AddAsync(order);
      await _context.SaveChangesAsync();



    • Attach to start Tracking



                  Hamper hamper = new Hamper { Id = 1, Name = "H1" };
      _context.Attach(hamper);
      OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id, Hamper = hamper };
      Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
      await _context.Order.AddAsync(order);
      await _context.SaveChangesAsync();



    • Or, you could pass the HamperId without Hamper



                  Hamper hamper = new Hamper { Id = 1, Name = "H1" };
      OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id };
      Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
      await _context.Order.AddAsync(order);
      await _context.SaveChangesAsync();







    share|improve this answer


























      0














      For EF Core to decide whether to update or create, it is controlled by Tracking. For your scenario, it seems you initialize a new Hamper when create a new Order with a new OrderItem.



      Try options below:





      • Reset Hamper with Hamper in database.



                Hamper hamper = new Hamper { Id = 1, Name = "H1" };
        Hamper dbHamper = _context.Hamper.FirstOrDefault(h => h.Id == hamper.Id);
        OrderItem orderItem = new OrderItem { Title = "T1", HamperId = dbHamper.Id, Hamper = dbHamper };
        Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
        await _context.Order.AddAsync(order);
        await _context.SaveChangesAsync();



      • Attach to start Tracking



                    Hamper hamper = new Hamper { Id = 1, Name = "H1" };
        _context.Attach(hamper);
        OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id, Hamper = hamper };
        Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
        await _context.Order.AddAsync(order);
        await _context.SaveChangesAsync();



      • Or, you could pass the HamperId without Hamper



                    Hamper hamper = new Hamper { Id = 1, Name = "H1" };
        OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id };
        Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
        await _context.Order.AddAsync(order);
        await _context.SaveChangesAsync();







      share|improve this answer
























        0












        0








        0






        For EF Core to decide whether to update or create, it is controlled by Tracking. For your scenario, it seems you initialize a new Hamper when create a new Order with a new OrderItem.



        Try options below:





        • Reset Hamper with Hamper in database.



                  Hamper hamper = new Hamper { Id = 1, Name = "H1" };
          Hamper dbHamper = _context.Hamper.FirstOrDefault(h => h.Id == hamper.Id);
          OrderItem orderItem = new OrderItem { Title = "T1", HamperId = dbHamper.Id, Hamper = dbHamper };
          Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
          await _context.Order.AddAsync(order);
          await _context.SaveChangesAsync();



        • Attach to start Tracking



                      Hamper hamper = new Hamper { Id = 1, Name = "H1" };
          _context.Attach(hamper);
          OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id, Hamper = hamper };
          Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
          await _context.Order.AddAsync(order);
          await _context.SaveChangesAsync();



        • Or, you could pass the HamperId without Hamper



                      Hamper hamper = new Hamper { Id = 1, Name = "H1" };
          OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id };
          Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
          await _context.Order.AddAsync(order);
          await _context.SaveChangesAsync();







        share|improve this answer












        For EF Core to decide whether to update or create, it is controlled by Tracking. For your scenario, it seems you initialize a new Hamper when create a new Order with a new OrderItem.



        Try options below:





        • Reset Hamper with Hamper in database.



                  Hamper hamper = new Hamper { Id = 1, Name = "H1" };
          Hamper dbHamper = _context.Hamper.FirstOrDefault(h => h.Id == hamper.Id);
          OrderItem orderItem = new OrderItem { Title = "T1", HamperId = dbHamper.Id, Hamper = dbHamper };
          Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
          await _context.Order.AddAsync(order);
          await _context.SaveChangesAsync();



        • Attach to start Tracking



                      Hamper hamper = new Hamper { Id = 1, Name = "H1" };
          _context.Attach(hamper);
          OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id, Hamper = hamper };
          Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
          await _context.Order.AddAsync(order);
          await _context.SaveChangesAsync();



        • Or, you could pass the HamperId without Hamper



                      Hamper hamper = new Hamper { Id = 1, Name = "H1" };
          OrderItem orderItem = new OrderItem { Title = "T1", HamperId = hamper.Id };
          Order order = new Order { OrderNo = "O1", OrderItem = orderItem };
          await _context.Order.AddAsync(order);
          await _context.SaveChangesAsync();








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 at 3:19









        Tao Zhou

        4,87031128




        4,87031128






























            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.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • 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%2f53443462%2fentity-framework-core-cannot-insert-explicit-value-when-saving-to-another-tabl%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)