当前位置:Gxlcms > 数据库问题 > EF-使用迁移技术让程序自动更新数据库表结构

EF-使用迁移技术让程序自动更新数据库表结构

时间:2021-07-01 10:21:17 帮助过:75人阅读

Configuration() { //将AutomaticMigrationsEnabled设置true,表示启用自动迁移技术 AutomaticMigrationsEnabled = true; //将AutomaticMigrationDataLossAllowed设置为true,表示在更新数据表结构时,允许丢失数据 AutomaticMigrationDataLossAllowed = true; ContextKey = "DAL.DemoContext"; }

如果该Configuration与应用程序不是在同一程序集,则需要将该Configuration类的访问修饰符从internal改为public。这样,在应用程序中才能使用该Configuration类。

 

3、使用迁移

在控制台应用程序的Main方法中,加上Database.SetInitializer(new MigrateDatabaseToLatestVersion<DemoContext, DAL.Migrations.Configuration>())。如下图所示:

技术分享

接下来运行程序。程序成功运行后,让我们来对比一下结果。

数据表结构更新前:

技术分享

 

数据表结构更新后:

技术分享

使用程序自动更新表结构成功!

 

4、模型类属性的特性约束

看一下上面的表结构,Name和Address的最大长度为max。

我们能否自定义一个最大的字符串长度呢?当然可以!

能否自动更新到表结构呢?你当我上面的那一篇幅文章是白讲的吗!!!

更新Model层的Student类,给某些字段添加特性约束。属性的特性约束,不仅在程序中可以使用,也能自动更新到数据库。如下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model {
    //指定表名
    [Table("Student")]
    public class Student {
        //指定该表的主键
        [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid ID { get; set; }

        [MaxLength(50,ErrorMessage ="姓名的最大长度为50个字符")]
        public string Name { get; set; }

        [Range(typeof(DateTime),"1900-01-01","2017-07-01")]
        public DateTime? BirthDay { get; set; }

        [Range(1,150,ErrorMessage ="年龄范围在1~150岁之间")]
        public int? Age { get; set; }

        [MaxLength(100,ErrorMessage ="地址的最大长度为100个字符")]
        public string Address { get; set; }
    }
}

运行程序后,我们看一下数据库中的表结构:

技术分享

已经成功更新了Student表结构。

惊不惊喜?

意不意外?

高不高兴?

开不开心?

在CodeFirst模式中,我们没有动过数据库一个代码,完全靠的是ORM框架去映射实体模型和数据库。只在程序代码中动动手指头,就能轻轻松松的调用数据库,使用数据。

 

EF-使用迁移技术让程序自动更新数据库表结构

标签:option   ror   最大的   blog   generic   image   技术分享   当前时间   程序代码   

人气教程排行