码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-10-27 00:21:22      阅读:260      评论:0      收藏:0      [点我收藏+]

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

一、创建数据库表

      运行数据库: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   

原文地址:http://www.cnblogs.com/leadoor/p/6002166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!