zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    Spring 学习笔记
    Hello Spring(3)ConnectionUtility
    android ndk开发
    java udp 广播及socket通讯
    android 横向滚动屏幕实现(2)
    android 基于ftp远程文件管理
    android 软键盘的弹出问题总结
    android 滚动字幕
    android 基于apache ftp server
    android 设置壁纸几种方法
  • 原文地址:https://www.cnblogs.com/nocanstillbb/p/11494987.html
Copyright © 2011-2022 走看看