Suppose you have a table Authors, the primary key is AuthorId
Author author = new Author() { AuthorId = 1001, Name = "Johny", Books = new List<Book> { new Book() { Title = "Learn VB.NET"}, new Book() { Title = "C# Fundamentals for Absolute Beginners"}, } };
You want to save the map, but you specify a primary key value is 1001, where you can not directly savechanges, you should first open the IDENTITY_INSERT, save and then delete
using (var context = new BookStore()) { Author author = new Author() { AuthorId = 1001, Name = "Johny", Books = new List<Book> { new Book() { Title = "Learn VB.NET"}, new Book() { Title = "C# Fundamentals for Absolute Beginners"}, } }; context.Authors.Add(author); context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Authors] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Authors] OFF"); }
But then the saved data id is not 1001, but will generate a database of identity numbers
The solution is to subclass a datacontext rewrite OnModelCreating
public class TempBookStore : BookStore { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Author>() .Property(a => a.AuthorId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); base.OnModelCreating(modelBuilder); } }
Then savechangs in a transaction
using (var context = new TempBookStore()) { using (var transaction = context.Database.BeginTransaction()) { Author author = new Author() { AuthorId = 1001, Name = "Johny", Books = new List<Book> { new Book() { Title = "Learn VB.NET"}, new Book() { Title = "C# Fundamentals for Absolute Beginners"}, } }; context.Authors.Add(author); context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Authors] ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [dbo].[Authors] OFF"); transaction.Commit(); } }