美文网首页.NET Coreasp.netdotnet core
创建ASP.NET Core MVC应用程序(3)-基于Ent

创建ASP.NET Core MVC应用程序(3)-基于Ent

作者: CharlieChu | 来源:发表于2016-11-21 16:52 被阅读497次

    创建ASP.NET Core MVC应用程序(3)-�基于Entity Framework Core(Code First)创建MySQL数据库表

    创建数据模型类(POCO类)

    Models文件夹下添加一个User类:

    namespace MyFirstApp.Models
    {
        public class User
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
            public string Bio { get; set; }
        }
    }
    

    除了你期望的用来构建Movie模型的属性外,将作为数据库主键的ID字段是必须的。

    安装Entity Framework Core MySQL相关依赖项

    注:其中"MySql.Data.EntityFrameworkCore": "7.0.6-ir31",要7.0.6以上版本。
    Missing implementation for running EntityFramework Core code first migration

    创建Entity Framework Context数据库上下文

    Models文件夹下添加一个UserContext类:

    /// <summary>
    /// The entity framework context with a User DbSet
    /// > dotnet ef migrations add MyMigration
    /// </summary>
    public class UserContext : DbContext
    {
        public DbSet<User> Users { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    
            var configuration = builder.Build();
    
            string connectionString = configuration.GetConnectionString("MyConnection");
    
            optionsBuilder.UseMySQL(connectionString);
        }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<User>().HasKey(m => m.ID);
            base.OnModelCreating(builder);
        }
    }
    

    OnConfiguring方法里面的指定使用MySQL provider及具体的连接字符串等逻辑也可以统一放到Startup类中的ConfigureServices方法中:

    public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = Configuration.GetConnectionString("MyConnection");
    
        services.AddDbContext<UserContext>(options =>
            options.UseMySQL(connectionString)
        );
    
        // Add framework services.
        services.AddMvc();
    }
    

    注:UseMySQLMySQL.Data.EntityFrameworkCore.Extensions里面的一个扩展方法,所以要手动添加using MySQL.Data.EntityFrameworkCore.Extensions;命名空间。这个小问题也花费了我不少的时间和精力。

    创建数据库

    通过Migrations工具来创建数据库。

    运行dotnet ef migrations add MyMigration Entity Framework .NET Core CLI Migrations命令来创建一个初始化迁移命令。

    运行dotnet ef database update应用一个你所创建的新的迁移到数据库。因为你的数据库还没不存在,它会在迁移�被应用之前为你创建所需的数据库。

    然后就会在项目生成Migrations文件夹,包括20161121064725_MyMigration.cs文件、20161121064725_MyMigration.Designer.cs文件和UserContextModelSnapshot.cs文件:

    20161121064725_MyMigration.Designer.cs类:

    [DbContext(typeof(UserContext))]
    [Migration("20161121064725_MyMigration")]
    partial class MyMigration
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.0-rtm-21431");
    
            modelBuilder.Entity("MyFirstApp.Models.User", b =>
                {
                    b.Property<int>("ID")
                        .ValueGeneratedOnAdd();
    
                    b.Property<string>("Bio");
    
                    b.Property<string>("Email");
    
                    b.Property<string>("Name");
    
                    b.HasKey("ID");
    
                    b.ToTable("Users");
                });
        }
    }
    

    20161121064725_MyMigration.cs Partial类:

    public partial class MyMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Users",
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("MySQL:AutoIncrement", true),
                    Bio = table.Column<string>(nullable: true),
                    Email = table.Column<string>(nullable: true),
                    Name = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Users", x => x.ID);
                });
        }
    
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Users");
        }
    }
    

    UserContextModelSnapshot类:

    [DbContext(typeof(UserContext))]
    partial class UserContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.0.0-rtm-21431");
    
            modelBuilder.Entity("MyFirstApp.Models.User", b =>
                {
                    b.Property<int>("ID")
                        .ValueGeneratedOnAdd();
    
                    b.Property<string>("Bio");
    
                    b.Property<string>("Email");
    
                    b.Property<string>("Name");
    
                    b.HasKey("ID");
    
                    b.ToTable("Users");
                });
        }
    }
    

    新创建的数据库结构如下:

    将上述的Migrations文件夹中的代码与MySQL数据库表__EFMigrationsHistory对照一下,你会发现该表是用来跟踪记录实际已经应用到数据库的迁移信息。

    创建User实例并将实例保存到数据库

    public class Program
    {
        public static void Main(string[] args)
        {
            using (var db = new UserContext())
            {
                db.Users.Add(new User { Name = "Charlie Chu", Email = "charlie.thinker@aliyun.com", Bio = "I am Chalrie Chu." });
                var count = db.SaveChanges();
    
                Console.WriteLine("{0} records saved to database", count);
    
                Console.WriteLine();
    
                Console.WriteLine("All users in database:");
                foreach (var user in db.Users)
                {
                    Console.WriteLine(" - {0}", user.Name);
                }
            }
        }
    }
    

    参考文档

    个人博客

    我的个人博客

    相关文章

      网友评论

      • 定海小蜗牛:楼主应该贴上appsettings.json配置信息会更好一些,可以学着操作下来

      本文标题:创建ASP.NET Core MVC应用程序(3)-基于Ent

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