Net Core mvc 使用mysql
NET Core 入門到產(chǎn)品化開發(fā)
第一部分:搭建你的服務(wù)器環(huán)境
- NET CORE 環(huán)境選擇
- 安裝Centos7
- Centos7 網(wǎng)絡(luò)配置 設(shè)置靜態(tài)Ip
- Centos7 服務(wù)器遠(yuǎn)程連接
- Centos7 安裝jexus5.8.2
第二部分:centos7 helloworld
第三部分:數(shù)據(jù)交互
在這個教程中或渤。你會創(chuàng)建NET Core mvc 項(xiàng)目系冗,使用Entity Framework Core nuget包,數(shù)據(jù)庫使用mysql
注意:
- 教程使用ORM數(shù)據(jù)交互
- NET Core 1.1
- Visual Studio 2017
創(chuàng)建項(xiàng)目
- 在你的項(xiàng)目文件中創(chuàng)建NET Core mvc 項(xiàng)目
安裝Pomelo.EntityFrameworkCore.MySql nuget包
Entity Framework Core 匹配的MySql有三個
- MySql官網(wǎng)
- Pomelo
- Sapient Guardian
我選擇的是Pomelo.EntityFrameworkCore.MySql 薪鹦,我本意是使用MySql官網(wǎng)掌敬,但是官網(wǎng)現(xiàn)在只有預(yù)覽版,并且我沒有找到開源項(xiàng)目池磁,所有我最后決定使用Pomelo奔害。
創(chuàng)建上下文和User實(shí)體
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服務(wù)配置添加上下文
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));
}
添加控制器和視圖
-
項(xiàng)目模板基架可用
選中** Controller 文件夾,鼠標(biāo)右鍵地熄,選擇添加 **
單擊添加 华临,選擇Minimal Dependencies 如果你的項(xiàng)目中模板基架已經(jīng)可以用了
選中** Controller 文件夾,鼠標(biāo)右鍵端考,選擇添加 ** 银舱,然后在選擇控制器
選中 **視圖使用 Entity Framework的 MVC 控制器 **在控制器構(gòu)造函數(shù)添加數(shù)據(jù)庫實(shí)例化(EnsureCreated)
public UsersController(BlogContext context)
{
_context = context;
_context.Database.EnsureCreated();
}
Startup修改默認(rèn)路由為users
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Users}/{action=Index}/{id?}");
});