当前位置:Gxlcms > 数据库问题 > .NET Core、Docker、Mysql简单之旅(二)

.NET Core、Docker、Mysql简单之旅(二)

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

一、创建数据库表

      运行数据库:docker restart local-mysql

      用Mysql客户端创建Employees数据库表

      表名:Employees

      Id: int(11) 主键,自动递增
      Name: varchar(32)
      LastName: varchar(32)

 

二、修改project.json

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.EntityFrameworkCore": "1.0.1",
    "MySql.Data.Core": "7.0.4-ir-191",
    "MySql.Data.EntityFrameworkCore": "7.0.4-ir-191"   
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

三、添加SampleContext.cs

using Microsoft.EntityFrameworkCore;
using MySQL.Data.EntityFrameworkCore.Extensions;

namespace StartMysql{
    public class EmployeesContext :DbContext {
        public EmployeesContext(DbContextOptions<EmployeesContext> options) : base(options) { }

        public DbSet<Employee> Employees { get; set; }
    }

    public static class EmployeesContextFactory {
        public static EmployeesContext Create(string connectionString) {
            var optionsBuilder = new DbContextOptionsBuilder<EmployeesContext>();
            optionsBuilder.UseMySQL(connectionString);

            var context = new EmployeesContext(optionsBuilder.Options);
            context.Database.EnsureCreated();            
            return context;
        }
    }  

    public class Employee {
        public Employee() { }

        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }

    }
}

四、修改Program.cs

using System;

namespace StartMysql
{
    public class Program
    {
        public static void Main(string[] args)
        {
            createEmployee();
        }

        public static void createEmployee() {
            var entry = new Employee() { Name = "John", LastName = "Winston" };
             
            using (var context = EmployeesContextFactory.Create(@"server=localhost;userid=root;pwd=root;port=3306;database=mysql;sslmode=none;"))
            {
               context.Add(entry);
               context.SaveChanges();
            }
             
            Console.WriteLine($"Employee was saved in the database with id: {entry.Id}");           

        }
    }
}

五、执行程序     

      dotnet restore

      dotnet run

      技术分享

.NET Core、Docker、Mysql简单之旅(二)

标签:end   microsoft   new   line   employees   root   deb   doc   alt   

人气教程排行