asp.net core webapi 使用ef 对mysql进行增删改查,并生成Docker镜像构建容器运行

1.构建运行mysql容器,添加数据库user

参考Docker创建运行多个mysql容器,地址 http://www.cnblogs.com/heyangyi/p/9288402.html

添加user数据库,添加tbusers表

2.创建asp.net core webapi 应用程序

参考Docker 为 ASP.NET Core WebApi 应用程序生成 Docker 映像,创建容器并运行,地址 http://www.cnblogs.com/heyangyi/p/9323407.html

<2.1> 修改 appsettings.json  文件,添加 dbconn 数据库链接配置

 

<2.2> 新增Config类,用来存储配置

    public class Config
    {
        public static string dbconn;
    }

<2.3> 修改Program 类,读取配置

    public class Program
    {
        private static IConfigurationRoot Configuration { get; set; }

        public static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json");

            Configuration = builder.Build();
            Config.dbconn = Configuration.GetValue<string>("dbconn");

            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }

<2.4> 新增DataContext类

安装引用:MySql.Data.EntityFrameworkCore

    public class DataContext : DbContext
    {
        public DbSet<tbuser> tbusers { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseMySQL(Config.dbconn);
    }
    public class tbuser
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int id { get; set; }
        public string nickName { get; set; }
        public string email { get; set; }
    }

<2.5> 新增tbuserDataHandle类

    public class tbuserDataHandle : DataContext
    {
        public static int adduser(tbuser user)
        {
            try
            {
                using (var context = new DataContext())
                {
                    context.Database.EnsureCreated();
                    context.Add(user);

                    context.SaveChanges();
                }
                return 200;
            }
            catch (Exception ex)
            {
                return 300;
            }
        }

        public static List<tbuser> Get()
        {
            try
            {
                using (var context = new DataContext())
                {
                    var users = context.tbusers;
                    List<tbuser> items = new List<tbuser>();
                    foreach (var item in users)
                    {
                        items.Add(item);
                    }
                    return items;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static tbuser Get(int id)
        {
            try
            {
                using (var context = new DataContext())
                {
                    var u = context.tbusers.Find(id);
                    return u;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static int Delete(int id)
        {
            try
            {
                using (var context = new DataContext())
                {
                    var u = context.tbusers.Remove(new tbuser() { id = id });
                    context.SaveChanges();
                    return 200;
                }
            }
            catch (Exception ex)
            {
                return 300;
            }
        }

        public static int Put(int id, tbuser user)
        {
            try
            {
                using (var context = new DataContext())
                {
                    var u = context.tbusers.Update(user);
                    context.SaveChanges();
                    return 200;
                }
            }
            catch (Exception ex)
            {
                return 300;
            }
        }
    }

<2.6> 新增userController Api

    [Produces("application/json")]
    [Route("api/user")]
    public class userController : Controller
    {
        // POST api/user
        [HttpPost]
        public int Post(tbuser user)
        {
            return tbuserDataHandle.adduser(user);
        }

        // GET api/user
        [HttpGet]
        public List<tbuser> Get()
        {
            return tbuserDataHandle.Get();
        }

        // GET api/user/5
        [HttpGet("{id}")]
        public tbuser Get(int id)
        {
            return tbuserDataHandle.Get(id);
        }

        // DELETE api/user/5
        [HttpDelete("{id}")]
        public int Delete(int id)
        {
            return tbuserDataHandle.Delete(id);
        }

        // PUT api/user/5
        [HttpPut("{id}")]
        public int Put(int id, tbuser user)
        {
            return tbuserDataHandle.Put(id, user);
        }
    }

3.生成项目,构建docker镜像并创作容器运行

修改 docker-compose.yml ,docker-compose.override.yml  的 version 为:

 version: '2.0'

配置 appsettings.json 的 dbconn 为:

"dbconn": "server=192.168.99.100;user id=root;password=123456;persistsecurityinfo=True;port=3307;database=user;SslMode=none"

进入到 E:\web\ilinkcore (这个目录为解决方案的根目录)

docker-compose up

  • up 自动完成包括构建镜像,创建服务,启动服务并关联服务容器的一系列操作

执行成功后创建一个 ilinkcore 的镜像,并且运行了一个 ilinkcore_ilinkcore_1的容器,将本机的32783端口映射到容器的80端口

4.测试访问接口

添加反向代理,修改nginx 配置

server{
    listen       84;
    server_name  localhost;
    location / {  
        proxy_pass   http://192.168.99.100:32783;  
        index  index.html index.htm;  
    }       
}

重新运行nginx,使用Postman进行api接口测试

<4.1> 测试接口进行添加user数据

Headers 中添加项:

Content-Type:application/json

<4.2>查看所有用户数据

<4.3> 检索某个用户数据

<4.4> 更新某个用户数据

Headers 中添加项:

Content-Type:application/json

<4.5> 删除单个用户

 

posted @ 2018-07-18 14:47  小何同學  阅读(2523)  评论(0编辑  收藏  举报