8.自增主键 插入指定主键的数据
Posted nocanstillbb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
以上是关于8.自增主键 插入指定主键的数据的主要内容,如果未能解决你的问题,请参考以下文章