美文网首页.Net Core微说集
.net core EF Code First

.net core EF Code First

作者: 张中华 | 来源:发表于2018-07-08 19:09 被阅读279次

    由于个人网站需要,现在学习下在.net core 下的EF(code first):学习地址

    1.创建.net core webapi 项目(随意):

    2.项目创建完成之后通过程序包管理器控制台,引入下面两个包

     Install-Package Microsoft.EntityFrameworkCore.Tools
    Install-Package Pomelo.EntityFrameworkCore.MySql
    

    有点麻烦,遇到两个警告,解决下:


    第一个警告先不管了吧,重新安装好.net core sdk 和runtime,就能依赖安装了。


    3. 添加数据表类:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
    
    
    namespace MyBlogNew.Entity
    {
        [Table("diary")]
        public class diary
        {
            [Key]
            [Column("Id")]
            public int Id { get; set; }
            [Column("Content")]
            public string Content { get; set; }
    
            [Column("Time")]
            public DateTime Time { get; set; }
    
            [Column("Week")]
            public string Week { get; set; }
            [Column("Weather")]
            public string Weather { get; set; }
            [Column("Mood")]
            public string Mood { get; set; }
            [Column("Hidden")]
            public bool Hidden { get; set; }
            [Column("Type")]
            public int Type { get; set; }
    
        }
    }
    

    4. 添加dataContext类

    using MyBlogNew.Entity;
    using Microsoft.EntityFrameworkCore;
    
    namespace MyBlogNew.Common
    {
        public class DataContext : DbContext
        {
            public DataContext(DbContextOptions<DataContext> options)
                : base(options)
            {
            }
            public DbSet<diary> Diary { get; set; }
        }
    }
    

    5. 打开Startup.cs 在ConfigurationServices方法中添加连接MySql的相关代码

     public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                //这里就是填写数据库的连接字符串
                var connection = "Server=localhost;Port=3306;Database=TestMySql; User=root;Password=;";
                services.AddDbContextPool<DataContext>(options => options.UseMySql(connection));
                
            }
    

    6. 初始化数据库,cmd执行

    dotnet ef Migrations add Init
    

    7.成功执行后,继续执行

    dotnet ef database update
    

    由于6,7是添加表用的,所以我这里因为已经存在该表,所以报错了。


    8.更新表,执行,竟然不行,麻烦,无法更新么?

    dotnet ef Migrations add UpdatediaryTable
    dotnet ef database update
    

    success

    dotnet ef migrations add diaryTableUpdate
    dotnet ef database update

    不知道如果存在数据的话,更新会不会删除原有数据呢,测试下:



    dotnet ef migrations add diaryTableUpdate1
    dotnet ef database update
    原有数据还是在的


    总结,就是执行 dotnet ef add Migrations add 自定义名称(注意是英文名称),这个名称每次是不同的,目前还不是很清楚这个名称的作用,是不是可以局限更新范围等功能,待有空研究。


    公众号.png

    相关文章

      网友评论

        本文标题:.net core EF Code First

        本文链接:https://www.haomeiwen.com/subject/ulpouftx.html