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

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


I'm trying to create an 'Order' object that has a Collection of 'OrderItem's that holds 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 :


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:

    public int Id { get; set; }
    public Hamper Hamper { get; set; }
    public int Quantity { get; set; }
    public int HamperID { get; set; }
4/17/2019 10:07:26 AM

Popular Answer

IDbContextTransaction trn = testDBContext.Database.BeginTransaction();
Item itm = new Item();
itm.ItemId = 23;
itm.ItemName = "item23";
Type typt = typeof(Item);
DbSet<Item> Item1 = testDBContext.Set<Item>();
testDBContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Item] ON");
//Item1.FromSql("SET IDENTITY_INSERT [dbo].[Item] ON").SingleOrDefaultAsync();


//Item1.FromSql("SET IDENTITY_INSERT [dbo].[Item] OFF").SingleOrDefaultAsync();
testDBContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[Item] OFF");
4/17/2019 10:25:46 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow