1.建立.net core的webapi项目参看:
2.在项目中添加MyDBContext类和实体类User
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestCore.Model
{
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Bio { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestCore.Model;
namespace TestCore
{
public class MyDBContext : DbContext
{
public MyDBContext(DbContextOptions options)
: base(options)
{
}
public DbSet User { get; set; }
}
}
3.在Startup类中的ConfigureServices方法添加如下代码:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext(options =>
options.UseMySQL(connectionString)
);
services.AddMvc();
}
appsetting.json中添加:
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;pwd=root;database=testcore;"
},
还有一种写法是在MyDBContext中配置链接字符串,好处是可以直接用new MyDBContext();初始化:
Startup类中:
public static IConfiguration Configuration { get; private set; }
MyDBContext类中:
public class MyDBContext : DbContext
{
//public MyDBContext(DbContextOptions options)
// : base(options)
//{
//}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = Startup.Configuration["ConnectionStrings:DefaultConnection"];
optionsBuilder.UseMySQL(connectionString);
}
public DbSet User { get; set; }
public DbSet Article { get; set; }
}4.控制台内执行
Add-Migration xxx
Update-Database
5.使用swagger
添加引用:Swashbuckle.AspNetCore
public void ConfigureServices(IServiceCollection services)
{
//使用mysql
var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext(options =>
options.UseMySQL(connectionString)
);
//Init Swagger
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "WebAPI"
});
//Determine base path for the application.
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
//Set the comments path for the swagger json and ui.
var xmlPath = Path.Combine(basePath, "TestCore.xml");//TestCore.xml是项目帮助文档,需要在项目属性-生成里开启文档
options.IncludeXmlComments(xmlPath);
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//InitSwagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI V1");
c.ShowRequestHeaders();
});
app.UseMvc();
}
6.发布到Linux环境,参考文章:
http://www.voidcn.com/article/p-ecxigwsg-brs.html