Entity framework 意外删除了表,如何在不影响其它表的情况下恢复回来(数据库迁移原理)

1. 关于EntityFramework数据迁移原理

查询数据库的表"__MigrationHistory",遍历Migrations文件夹下的所有文件,如果文件不在__MigrationHistory表内,那么就执行迁移。

有了上面的原理之后,我们来看一下如果我们不小心手动删除了一个表,如何在不影响其它表的情况下来恢复你删除的表:

方法一:

关于Model 以及 DBContext如下:

  

 1  public class Blog
 2     {
 3         public int BlogId { get; set; }
 4         public string Name { get; set; }
 5 
 6         public string Url { get; set; }
 7         public virtual List<Post> Posts { get; set; }
 8     }
 9 
10     public class User
11     {
12         [Key]
13         public int UserId { get; set; }
14         public string Username { get; set; }
15         public string DisplayName { get; set; }
16         //public int? age { get; set; }
17         //public string interest { get; set; }
18     }
19 
20     public class School
21     {
22         public int SchoolId { get; set; }
23 
24         public string SchoolName { get; set; }
25 
26         public int SchoolLevel { get; set; }
27     }
28 
29 
30     public class Teacher
31     {
32         [Key]
33         public int TecherId { get; set; }
34         public string TeacherName { get; set; }
35     }
36 
37 
38     public class Post
39     {
40         public int PostId { get; set; }
41         public string Title { get; set; }
42         public string Content { get; set; }
43 
44         public int BlogId { get; set; }
45         public virtual Blog Blog { get; set; }
46     }
47 
48     public class Tutorial
49     {
50         [Key]
51         public int Id { get; set; }
52 
53         public int Name { get; set; }
54     }
55 
56     public class BloggingContext : DbContext
57     {
58         public DbSet<Blog> Blogs { get; set; }
59         public DbSet<Post> Posts { get; set; }
60 
61         public DbSet<User> Users { get; set; }
62 
63         public DbSet<Tutorial> Tutorials { get; set; }
64         public DbSet<School> Schools { get; set; }
65 
66         public DbSet<Teacher> Teachers { get; set; }
67         protected override void OnModelCreating(DbModelBuilder modelBuilder)
68         {
69             modelBuilder.Entity<User>().Property(u => u.DisplayName).HasColumnName("display_name");
70             modelBuilder.Entity<User>().Property(u => u.Username).HasColumnName("user_name");
71         }
72     }

 

migrations 文件夹下的文件如下:

技术分享

对应数据库中的记录为:

技术分享

 

假如此时我们手动删除了schools表,此时我们应该找到schools表的创建与修改的迁移code是在哪个Migrations文件夹下面的哪个文件,找到对应的文件

我们这里是在201503190341085_addmodels.cs中,

 1   public partial class addmodels : DbMigration
 2     {
 3         public override void Up()
 4         {
 5             CreateTable(
 6                 "dbo.Blogs",
 7                 c => new
 8                     {
 9                         BlogId = c.Int(nullable: false, identity: true),
10                         Name = c.String(),
11                         Url = c.String(),
12                     })
13                 .PrimaryKey(t => t.BlogId);
14 
15             CreateTable(
16                 "dbo.Posts",
17                 c => new
18                     {
19                         PostId = c.Int(nullable: false, identity: true),
20                         Title = c.String(),
21                         Content = c.String(),
22                         BlogId = c.Int(nullable: false),
23                     })
24                 .PrimaryKey(t => t.PostId)
25                 .ForeignKey("dbo.Blogs", t => t.BlogId, cascadeDelete: true)
26                 .Index(t => t.BlogId);
27             
28             CreateTable(
29                 "dbo.Schools",
30                 c => new
31                     {
32                         SchoolId = c.Int(nullable: false, identity: true),
33                         SchoolName = c.String(),
34                         SchoolLevel = c.Int(nullable: false),
35                     })
36                 .PrimaryKey(t => t.SchoolId);
37 
38             CreateTable(
39                 "dbo.Tutorials",
40                 c => new
41                     {
42                         Id = c.Int(nullable: false, identity: true),
43                         Name = c.Int(nullable: false),
44                     })
45                 .PrimaryKey(t => t.Id);
46 
47             CreateTable(
48                 "dbo.Users",
49                 c => new
50                     {
51                         UserId = c.Int(nullable: false, identity: true),
52                         user_name = c.String(),
53                         display_name = c.String(),
54                     })
55                 .PrimaryKey(t => t.UserId);
56             
57         }
58         
59         public override void Down()
60         {
61             DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs");
62             DropIndex("dbo.Posts", new[] { "BlogId" });
63             DropTable("dbo.Users");
64             DropTable("dbo.Tutorials");
65             DropTable("dbo.Schools");
66             DropTable("dbo.Posts");
67             DropTable("dbo.Blogs");
68         }
69     }

此时我们要做的只要把这个文件名201503190341085_addmodels.cs对应在数据迁移表中的记录删除,

  delete __MigrationHistory where MigrationId = ‘201503190341085_addmodels‘ ,然后我们在201503190341085_addmodels.cs注释掉其它的迁移数据,只留下创建shools表的数据

 

 1     public partial class addmodels : DbMigration
 2     {
 3         public override void Up()
 4         {
 5             //CreateTable(
 6             //    "dbo.Blogs",
 7             //    c => new
 8             //        {
 9             //            BlogId = c.Int(nullable: false, identity: true),
10             //            Name = c.String(),
11             //            Url = c.String(),
12             //        })
13             //    .PrimaryKey(t => t.BlogId);
14 
15             //CreateTable(
16             //    "dbo.Posts",
17             //    c => new
18             //        {
19             //            PostId = c.Int(nullable: false, identity: true),
20             //            Title = c.String(),
21             //            Content = c.String(),
22             //            BlogId = c.Int(nullable: false),
23             //        })
24             //    .PrimaryKey(t => t.PostId)
25             //    .ForeignKey("dbo.Blogs", t => t.BlogId, cascadeDelete: true)
26             //    .Index(t => t.BlogId);
27             
28             CreateTable(
29                 "dbo.Schools",
30                 c => new
31                     {
32                         SchoolId = c.Int(nullable: false, identity: true),
33                         SchoolName = c.String(),
34                         SchoolLevel = c.Int(nullable: false),
35                     })
36                 .PrimaryKey(t => t.SchoolId);
37 
38             //CreateTable(
39             //    "dbo.Tutorials",
40             //    c => new
41             //        {
42             //            Id = c.Int(nullable: false, identity: true),
43             //            Name = c.Int(nullable: false),
44             //        })
45             //    .PrimaryKey(t => t.Id);
46 
47             //CreateTable(
48             //    "dbo.Users",
49             //    c => new
50             //        {
51             //            UserId = c.Int(nullable: false, identity: true),
52             //            user_name = c.String(),
53             //            display_name = c.String(),
54             //        })
55             //    .PrimaryKey(t => t.UserId);
56             
57         }
58         
59         public override void Down()
60         {
61             //DropForeignKey("dbo.Posts", "BlogId", "dbo.Blogs");
62             //DropIndex("dbo.Posts", new[] { "BlogId" });
63             //DropTable("dbo.Users");
64             //DropTable("dbo.Tutorials");
65             DropTable("dbo.Schools");
66             //DropTable("dbo.Posts");
67             //DropTable("dbo.Blogs");
68         }
69     }

此时如果你在package-manager console 中执行update-database 即可完成schools表的恢复

 

方法二:

利用 Update-Database -Script -SourceMigration $InitialDatabase这是一个变量不需要你去改成你自己的数据库名字  或者  

Update-Database -Script -SourceMigration Second -TargetMigration First (用这两个中的哪个是视情况而定的)
(Second First 就是你的migrations文件夹下的文件名字的后面那个 比喻 201503190906406_addmodels 你就输入 Update-Database -Script -SourceMigration addmodels)
这样会产生一个脚本文件,你在那个脚本文件中找出你恢复的表的一些创建或者修改信息
DECLARE @CurrentMigration [nvarchar](max)

IF object_id([dbo].[__MigrationHistory]) IS NOT NULL
    SELECT @CurrentMigration =
        (SELECT TOP (1) 
        [Project1].[MigrationId] AS [MigrationId]
        FROM ( SELECT 
        [Extent1].[MigrationId] AS [MigrationId]
        FROM [dbo].[__MigrationHistory] AS [Extent1]
        WHERE [Extent1].[ContextKey] = NEntityFrameworkStudy.Migrations.Configuration
        )  AS [Project1]
        ORDER BY [Project1].[MigrationId] DESC)

IF @CurrentMigration IS NULL
    SET @CurrentMigration = 0

IF @CurrentMigration < 201503190906406_addmodels
BEGIN
    CREATE TABLE [dbo].[Blogs] (
        [BlogId] [int] NOT NULL IDENTITY,
        [Name] [nvarchar](max),
        [Url] [nvarchar](max),
        CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY ([BlogId])
    )
    CREATE TABLE [dbo].[Posts] (
        [PostId] [int] NOT NULL IDENTITY,
        [Title] [nvarchar](max),
        [Content] [nvarchar](max),
        [BlogId] [int] NOT NULL,
        CONSTRAINT [PK_dbo.Posts] PRIMARY KEY ([PostId])
    )
    CREATE INDEX [IX_BlogId] ON [dbo].[Posts]([BlogId])
    CREATE TABLE [dbo].[Schools] (
        [SchoolId] [int] NOT NULL IDENTITY,
        [SchoolName] [nvarchar](max),
        [SchoolLevel] [int] NOT NULL,
        CONSTRAINT [PK_dbo.Schools] PRIMARY KEY ([SchoolId])
    )
    CREATE TABLE [dbo].[Teachers] (
        [TecherId] [int] NOT NULL IDENTITY,
        [TeacherName] [nvarchar](max),
        CONSTRAINT [PK_dbo.Teachers] PRIMARY KEY ([TecherId])
    )
    CREATE TABLE [dbo].[Tutorials] (
        [Id] [int] NOT NULL IDENTITY,
        [Name] [int] NOT NULL,
        CONSTRAINT [PK_dbo.Tutorials] PRIMARY KEY ([Id])
    )
    CREATE TABLE [dbo].[Users] (
        [UserId] [int] NOT NULL IDENTITY,
        [user_name] [nvarchar](max),
        [display_name] [nvarchar](max),
        CONSTRAINT [PK_dbo.Users] PRIMARY KEY ([UserId])
    )
    ALTER TABLE [dbo].[Posts] ADD CONSTRAINT [FK_dbo.Posts_dbo.Blogs_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [dbo].[Blogs] ([BlogId]) ON DELETE CASCADE
    CREATE TABLE [dbo].[__MigrationHistory] (
        [MigrationId] [nvarchar](150) NOT NULL,
        [ContextKey] [nvarchar](300) NOT NULL,
        [Model] [varbinary](max) NOT NULL,
        [ProductVersion] [nvarchar](32) NOT NULL,
        CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])
    )
    INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
    VALUES (N201503190906406_addmodels, NEntityFrameworkStudy.Migrations.Configuration,  0x1F8B0800000000000400D55B5F6FDB36107F1FB0EF20E8691B522B695FBAC06E913ACD10ACF983D82DF61630D2D9114A519A486536867DB23DEC23ED2BEC28EA3F29DB92FF7528502424EF78BCFBDDF178A7FCFBF73FC3F78B805A2F10733F6423FB6C706A5BC0DCD0F3D97C642762F6EAADFDFEDDF7DF0D3F7AC1C2FA92AF7B23D72125E323FB5988E8DC71B8FB0C01E183C077E39087333170C3C0215EE8BC3E3DFDD9393B730059D8C8CBB2860F09137E00E92FF8EB38642E442221F426F480F26C1C67262957EB9604C023E2C2C8FE8894627915E3C81F61FC7522126F695B17D42728CB04E8CCB60863A12002253DFFCC6122E290CD27110E103A5D4680EB668472C84E705E2EDFF430A7AFE5619C923067E5265C84414786676F32ED384DF25E3AB60BEDA1FE94B6E4A9531D8EEC0F349CDB5673A3F3318DE522B37A0792E8C4324D9D149840E8C87F27D638A1228961C4201131A127D67DF2447DF757584EC3AFC0462CA1B42A234A8973B5011CBA8FC30862B17C805945F26BCFB69C3AADD3242E481B74EA7CD74CBC796D5BB7280479A25040A1A28B890863F80518C44480774F8480182D79ED41AA004D82C67EF2FF7C37C41E3A926DDD90C5276073F13CB2F147DBBAF217E0E52399049F998F7E8744224E60DD269F63BAFB3D6EC98B3F4F75D0D8ED3EE482DBD603D074963FFB91F2B5819C795498BA8AC3E021A4D9F274F0714AE2390894346CCE4CC224761B220C9D12AE2B412CD97406B1243A3A88A5107D409CD31D0AC4535FD0FDA318E3BE4079F6BECF662160536F5070EFEE0C39E47567C8DDA49733E0151986B4B33B28B2A33B8412A38F4B949487720AB5E341E2BBDAEA13BC00ED02DB8D41330582B944DC193519DDD161330529461FD89494078BA54A677BC0CDE6E64EF00898FE76B77746787483F731F5B1B2BE9D7A2ABE60BABBA9243ABAC9A4107DCC96D31DCA74723F7688A07EE9F38892E50103C105E7A1EBA75AAA24922A47A98BFA9179566BC2A244CD531C941611E3478811DC7264FFA49DDBC4AC780A94CC54AA54677666378175C72E818200EBC2554FEA31E12EF1746DA30EBCFA0862116209024231D5E4886E9F091DB83E73FD88D036911B041D1EA752A8827D73E612226012A26D7ADF6EDF827D4349EB7432742AA0D123934CD99102E28A007384709ACA2F4CAF3274AF2C58F10CBA4DB048BE1310158EF8D82C015D438B86B43A71F652D588156ED710ABA4CB449EE7D86B186437BD89439170AD63915DB8461EC52DBE86898C682606EA2E691057CC5DD763F694A9CC6BEF9C26EA56459142C8C24A1A6857C58D0A798690A6FBD70F62888E0576CBFAA2A30A8C7921D269A9440E6F481421CA2B95C96CC49AA8B2E4F8D5A47BB52E503C1C971B8A7685B4C54E687D3287C6AC7C457B70E5C75C5C12419E88BC2AC65EA02D6B7A6A0B84F2DDAACEA8DB290756BE5AFEAC285A0B8886789651E3E2792003617A91370CAD93A565614249DCF2CA1F873409D8EAF8D8CE45DDCE551E6A64730E696DAECA201DD0E9874EE3FC5A0CD7F4AC5D7875A36D6452E57C5B9B348DA8DD4D6A266B53655EF6AA6AD35C425BC5252B66559964439BF3284A55552EC5E0E67CBA81F44810C92FC2AD4192DD9BDD61D246D8A6D6B21854556C5B71693D273D0A54C7BB72CBEA383ABB6CE29B317C91C06C6DF93CDFE96EFA56CA56F72E2A3A350F6FA910ADE654A9D4D4995526BE1D6B15B9E2F6E6CA53CB1EF66A256D5373D354FBBAA08F6416957D6F6D923459EF6E0E33596BAEC275CF31D76DD671619A59121C7D641D0366AD4652E5E6A98956867B35B6F682682E29762F5E128D17C330CBDED77FE0A0A5F36A896DA1A65E7C4FA6F2932517100CE482C1E4773AA67E9A85E40B6E08F367C0852ADFD9F8DA78DBF842E2DBF95AC1E1DCA386D74FF393851EF5C7DD7C30E04BCDAEAD30AE6B26AEA816B31712BBCF24FE21208B1FAB9C3A7E07D0814FB7467B0FD5EFA6CDBD17D5D73ADB5BE9BED1BDDE8A9701735A21ED9A79B018D97FA624E7D6F56F8F8AEAC4BA8BD1EBCFAD53EBAF5D751D4CF9F7A11BBA7B31BFDEC3DDCA6E863E6D2AF66EBBB43DCCB0BB06E97EBC50EF89EE237E9973D343741CF77E6DEC10667ACA78C806DF5E3455C93D77E0E5F5DC736770EDD39D5335F94336D1EA45F91EDDC05E5DB8968AF1DE3A6FFF8F6E9B5EEA6F7991D63E556B69A5A97705A2FB2944AB2AF09A5B2BA62E5B6B93CDC4D6D8F069E9BFAD68BF9958174DBBCD7A73AB5A7326F6654B6FC3C6DDCABE9D7187B2E3B7415BAFB5AB67629DF5010FD2F0AB42AD6CDEACEBF1696DC1FDB4F5F4C737BA66E56F103024707F5EB2907F91C0C0AD3965B1E69ACDC23C363424CA9734EE8F1B10C4438FBD88853F23AEC06917384FBFFCF84268224B40C11378D7EC2E115122F0C8103CD1DA972B32C6ACDA3FED5DD6651EDE45E917AABB38028AE9E311E08E7D487CEA15725F19F28E161632786557BCB4A59057FD7C5970BA0DD9868C32F51531770A015ECF02F81D9B9017E8231B7ACA2798137799D750DA99AC37445DEDC34B9FCC6312F08C47498FBF2286BD60F1EE3F49D43B5B8A330000 , N6.1.3-40302)
END

我找到了Schools的创建SQL , 在数据库中执行即可:

1      CREATE TABLE [dbo].[Schools] (
2         [SchoolId] [int] NOT NULL IDENTITY,
3         [SchoolName] [nvarchar](max),
4         [SchoolLevel] [int] NOT NULL,
5         CONSTRAINT [PK_dbo.Schools] PRIMARY KEY ([SchoolId])
6     )

这样你就恢复好了

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。