8.自增主键 插入指定主键的数据

假设你有一个表Authors ,主键是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"},
    }
};

你想保存这个图,但是你指定了主键的值是1001,这里你不能直接savechanges,你应该首先打开IDENTITY_INSERT,保存后再删除

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");
}

但是这时保存的数据的 id不是1001,而会是数据库identity生成的序号

解决的方法是派生一个 datacontext的子类重写OnModelCreating

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

然后在事务中savechangs

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();
    }
}

猜你喜欢

转载自www.cnblogs.com/nocanstillbb/p/11494987.html
今日推荐