您的位置:首页 > 数据库 > MySQL

Net Core mvc 使用mysql

2017-04-16 00:11 585 查看

Net Core mvc 使用mysql

NET Core 入门到产品化开发

NET Core 第一部分 : 搭建你的服器器

NET CORE 环境选择

安装Centos7

Centos7 网络配置 设置静态Ip

Centos7 服务器远程连接

Centos7 安装jexus5.8.2

NET Core 第二部分 : 搭建你的服器器

- NET Core helloworld

在这个教程中。你会创建NET Core mvc 项目,使用Entity Framework Core nuget包,数据库使用mysql

注意:

- 教程使用ORM数据交互

- NET Core 1.1

- Visual Studio 2017

创建项目

在你的项目文件中创建NET Core mvc 项目

安装Pomelo.EntityFrameworkCore.MySql nuget包

Entity Framework Core 匹配的MySql有三个

- MySql官网

- Pomelo

- Sapient Guardian

我选择的是Pomelo.EntityFrameworkCore.MySql ,我本意是使用MySql官网,但是官网现在只有预览版,并且我没有找到开源项目,所有我最后决定使用Pomelo。

创建上下文和User实体

using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace BlogApp.Models
{
public class BlogContext:DbContext
{
public BlogContext(DbContextOptions<BlogContext> options) : base(options)
{ }

public DbSet<User> Blogs { get; set; }
}

public class User
{
[Key]
public string Name { get; set; }

[Required]
public string PhoneNumber { get; set; }
}
}


Startup服务配置添加上下文

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();

var connection = @"Server=121.253.235.235;Database=blog;uid=automa;pwd=AutomaMySql_12";
services.AddDbContext<BlogContext>(options => options.UseMySql(connection));
}


添加控制器和视图

项目模板基架可用

选中* Controller 文件夹,鼠标右键,选择添加 *

单击添加 ,选择Minimal Dependencies

如果你的项目中模板基架已经可以用了

选中* Controller 文件夹,鼠标右键,选择添加 * ,然后在选择控制器

选中 视图使用 Entity Framework的 MVC 控制器

在控制器构造函数添加数据库实例化(EnsureCreated)

public UsersController(BlogContext context)
{
_context = context;
_context.Database.EnsureCreated();
}


Startup修改默认路由为users

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Users}/{action=Index}/{id?}");
});


运行项目

使用sqlyog连接服务,数据库已经建立

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql centos