Ceci est une ancienne révision du document !
https://entityframework.net/identity-insert
The solution is to create a new context class which will inherit our main context class and overrides the OnModelCreating.
public class TempBookStore : BookStore { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Author>() .Property(a => a.AuthorId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); base.OnModelCreating(modelBuilder); } }
In the OnModelCreating function we can set the attribute on the entity to not generate auto values for AuthorId. You will also need to make sure to wrap the SQL command and the row 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(); } }