Linq To Sql and identity_insert

后端 未结 6 1042
星月不相逢
星月不相逢 2021-01-13 04:29

I am trying to do record inserts on a table where the Primary Key is an Identity field.

I have tried calling
mycontext.ExecuteCommand("S

6条回答
  •  萌比男神i
    2021-01-13 05:03

    just simple reseed identity key (with custom id) every time you add new record, eg:

        using (var desDb = new DesDbContext())
        {
            // del-table-all --------------------------------------------------------
            desDb.Database.ExecuteSqlCommand("DELETE FROM [Products]");
    
            foreach (var desItem in desList) //desList is List of Product
            {
                // reseed identity key
                desDb.Database.ExecuteSqlCommand("DBCC CHECKIDENT('Products', RESEED," 
                    + (desItem.ProductID - 1) + ");");
    
                // and record
                desDb.Products.Add(desItem);                        
    
                // save-db                    
                desDb.SaveChanges();
    
            }
        }
    

提交回复
热议问题