使用EF Core建立Code First,完成数据库迁移。
使用sqlite数据库
1.建立一个.net core web api项目
2.安装Microsoft.EntityFrameworkCore.Sqlite
3. 建立一个实体
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
}
4.建立DataContext
继承DbContext,初始化构造函数,继承base,再把User类写入
public class DataContext : DbContext
{
public DataContext(DbContextOptions options)
: base(options)
{
}
public DbSet Users { get; set; }
}
5.配置数据库
var connrection = "FileName=./demo.db";
services.AddDbContext(options =>
{
options.UseSqlite(connrection);
});
这里可以把Sqlite,换成别的数据库地址
注意:这里必须写 FileName=./demo.db 否则后面生成的时候报错
6.安装Microsoft.EntityFrameworkCore.tools
7. 配置appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"tools": {
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-previewl-final",
"imports": [
"portable-net 45+win8+dnxcore50",
"portable-net 45+win8"
]
}
}
}
8.在程序包管理器控制台中,输入Add-Migration xxx
9.在输入Update-Database,创建数据库完成
9.使用
别忘记 context.SaveChanges();
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger _logger;
private readonly DataContext context;
public WeatherForecastController(ILogger logger,DataContext context)
{
_logger = logger;
this.context = context;
}
[HttpGet]
public IEnumerable Get()
{
User user = new User();
user.age = 15;
user.Id = 1;
user.Name = "张三";
context.Add(user);
context.SaveChanges();
var rng = new Random();
var n = context.Users.Where(n => n.Name == "张三");
foreach (var item in n)
{
Console.WriteLine(item.Name);
}
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}