EF - Identity Insert 1

CSharp · Console

/Program.cs

// @nuget: EntityFramework

using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;

public class Program
{
	public static void Main()
	{
		InsertData();
		
		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();
				
				FiddleHelper.WriteTable(context.Authors.ToList());
            }
        }
	}
	
	public static void InsertData()
	{
		using (var context = new BookStore())
		{
			Author author1 = new Author()
		    {
		        Name = "Mark",
		        Books = new List<Book>
				{
					new Book() { Title = "Fundamentals of Computer Programming with C#"},
					new Book() { Title = "Java: A Beginner's Guide"},
				}
		    };
			Author author2 = new Author()
		    {
		        Name = "Andy",
		        Books = new List<Book>
				{
					new Book() { Title = "SQL: The Ultimate Beginners Guide"}
				}
		    };
			
		    context.Authors.Add(author1);
			context.Authors.Add(author2);

		    context.SaveChanges();
		}
	}
	
	public class TempBookStore : BookStore
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Author>()
              .Property(a => a.AuthorId)
              .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
            base.OnModelCreating(modelBuilder);
        }
    }
	
	public class BookStore : DbContext
    {
        public BookStore() : base(FiddleHelper.GetConnectionStringSqlServer())
        {
        }
	

        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
    }

     public class Book
	{
    	public int BookId { get; set; }
	    public string Title { get; set; }
	    public int AuthorId { get; set; }
	    [ForeignKey("AuthorId")]
    	public Author Author { get; set; }
	}

    public class Author
	{
    	public int AuthorId { get; set; }
    	public string Name { get; set; }
		public virtual ICollection<Book> Books { get; set; }
	}
}
;