• 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();
        }
    }
  • 相关阅读:
    CF703D Mishka and Interesting sum
    CF697D Puzzles
    SCOI2017酱油记
    [BZOJ4730][清华集训2016][UOJ266] Alice和Bob又在玩游戏
    BZOJ4311:向量
    BZOJ4520: [Cqoi2016]K远点对
    BZOJ4555: [Tjoi2016&Heoi2016]求和
    [Codechef November Challenge 2012] Arithmetic Progressions
    agc040
    补题
  • 原文地址:https://www.cnblogs.com/nocanstillbb/p/11494987.html
Copyright © 2020-2023  润新知