码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-09-10 00:47:14      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:new   int   tran   插入   ati   有一个   tor   一个   是你   

假设你有一个表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.自增主键 插入指定主键的数据

标签:new   int   tran   插入   ati   有一个   tor   一个   是你   

原文地址:https://www.cnblogs.com/nocanstillbb/p/11494987.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!