.Net Core 的WebApi项目使用mysql的EF CodeFirst模式
注.建立.net core的webapi项目参看:
http://blog.csdn.net/zzzili/article/details/75307308
1.需要引用的库有
或者
2.在项目中添加MyDBContext类和实体类User
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataCore
{
public class User
{
public int id { set; get; }
public string remark1 { set; get; }
public string name { set; get; }
public int age { set; get; }
public string remark2 { set; get; }
public DateTime updateTime { set; get; }
public DateTime createTime { set; get; }
public bool isEnable { set; get; }
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataCore
{
public class MyDBContext : DbContext
{
public MyDBContext(DbContextOptions<MyDBContext> options)
: base(options)
{
}
public DbSet<User> User { get; set; }
}
}
3.在Startup类中的ConfigureServices方法添加如下代码:
public void ConfigureServices(IServiceCollection services)
{
// Replace with your connection string.
var connectionString= Configuration["ConnectionStrings:DefaultConnection"];
//Pomelo时这样写
var serverVersion = new MySqlServerVersion(new Version(5, 6, 22));
services.AddDbContext<MyDBContext>(options =>options.UseMySql(connectionString,serverVersion));
//或者用mysql ef core时这样写
services.AddDbContext<MyDBContext>(options =>options.UseMySQL(connectionString));
services.AddControllers();
}
appsetting.json中添加:
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;pwd=root;database=testcore;"
},
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataCore
{
public class MyDBContext : DbContext
{
public static string connectionString = null;
public MyDBContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL(connectionString);
}
public DbSet<User> User { get; set; }
}
}
//Startup中这样配置,把连接字符串赋值给MyDBContext的静态变量
public void ConfigureServices(IServiceCollection services)
{
// Replace with your connection string.
var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
MyDBContext.connectionString = connectionString;
services.AddControllers();
}
Add-Migration xxx
Update-Database
5.使用swagger
添加引用:Swashbuckle.AspNetCore
public void ConfigureServices(IServiceCollection services)
{
//使用mysql
var connectionString= Configuration["ConnectionStrings:DefaultConnection"];
var serverVersion = new MySqlServerVersion(new Version(5, 6, 22));
services.AddDbContext<MyDBContext>(options =>
options.UseMySql(connectionString,serverVersion));
//Init Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//InitSwagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});
app.UseMvc();
}
6.TestController
using DataCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3.Controllers
{
public class TestInput
{
public string str1 { set; get; }
public string str2 { set; get; }
}
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpPost]
public string test2(TestInput input)
{
return input.str1+input.str2;
}
private readonly MyDBContext dbContext = new MyDBContext();
[HttpGet]
public object testmysql()
{
User u = new User();
u.remark1 = "1";
u.createTime = DateTime.Now;
dbContext.User.Add(u);
dbContext.SaveChanges();
var list = dbContext.User.ToList();
return list;
}
}
}
7.发布到Linux环境,参考文章:http://blog.csdn.net/zzzili/article/details/79213001
***************************************************************************************************************************************************************************************************
完整文件
MyDBContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataCore
{
public class MyDBContext : DbContext
{
public static string connectionString = null;
public MyDBContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL(connectionString);
}
public DbSet<User> User { get; set; }
public DbSet<UserOrder> UserOrder { get; set; }
}
}
Startup.cs
using DataCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Replace with your connection string.
var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
MyDBContext.connectionString = connectionString;
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
//InitSwagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json", "My API V1");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
TestController.cs
using DataCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3.Controllers
{
public class TestInput
{
public string str1 { set; get; }
public string str2 { set; get; }
}
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpPost]
public string test2(TestInput input)
{
return input.str1+input.str2;
}
private readonly MyDBContext dbContext = new MyDBContext();
[HttpGet]
public object testmysql()
{
UserOrder u = new UserOrder();
u.userId =1;
u.orderNo = "11111";
dbContext.UserOrder.Add(u);
dbContext.SaveChanges();
var query = from user in dbContext.User
join o in dbContext.UserOrder on
u.id equals o.userId
select new { user,o};
var list = query.ToList();
return list;
}
}
}
文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。
原文链接:zzzili.blog.csdn.net/article/details/79202157
- 点赞
- 收藏
- 关注作者
评论(0)