.net core 引入ef core 模式之 codefirst


这章主要是说:.net core中使用ef  core 框架中的codefirst模式去处理数据库方面的使用说明,以下是官方连接

https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/  

EF与EF core我在使用方面最大的一个不同点就是:

EF通过code配置后,可以达到更改属性后,同时改动数据库表或字段:

1   public EFDbcontext()
2             : base(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString)
3         {
4 
5             Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFDbcontext, Configuration<EFDbcontext>>());
6         }

而EF Core 更改model后 并不能让数据库与其同步,需要 通过命令来操作,如下:

将Student.Title 重命名为Student.Title222,需要对应的迁移命令如下:

Add-Migration ChangeName
Update-Database

注意!实际上改完的操作为:删除了数据库中的列Title 新增列Title222,与需求不符合

改完之后会在Migrations文件夹有对应的code文件生成,如上操作,会产生如下code: (还不知道这个框架能不能给解决这样的问题)

 public partial class ChangeTitle222 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Title",
                table: "Student");

            migrationBuilder.AddColumn<string>(
                name: "Title222",
                table: "Student",
                maxLength: 255,
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Title222",
                table: "Student");

            migrationBuilder.AddColumn<string>(
                name: "Title",
                table: "Student",
                type: "nvarchar(255)",
                maxLength: 255,
                nullable: true);
        }
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM