下面例子是用的Mysql数据库,所以我引用的sdk是Pomelo.EntityFrameworkCore.MySql
如果你是用的SqlServer 应该引用sql对应的sdk(Microsoft.EntityFrameworkCore.SqlServer)
一:第一种方法(sdk3.1)
启动项和上下文在一个类库里面
1.创建一个数据库模型
public class Movies
{
/// <summary>
/// id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Title { get; set; }
/// <summary>
/// 时间
/// </summary>
public DateTime ReleaseDate { get; set; }
/// <summary>
/// 类型
/// </summary>
[Required(AllowEmptyStrings = false)]
public string Genre { get; set; }
/// <summary>
/// 价格
/// </summary>
public decimal Price { get; set; }
}
2.在上下文中
继承DbContext类
public class FilmContext : DbContext
{}
3.在上下文中build字段到数据库
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var etMovie = modelBuilder.Entity<Movie>().ToTable("t_movie");
etMovie.Property(e => e.Id).IsRequired();//不写IsRequired,默认为可空
etMovie.Property(e => e.Title).IsRequired();
etMovie.Property(e => e.Re