一、与数据库表映射
1、安装依赖:Install-Package Microsoft.EntityFrameworkCore.SqlServer;
2、创建实体类:
public record Person { public long? Id { get;set; } public string Name { get; set; } public string BloodType { get; set; } public bool Genger { get; set; } public DateTime? BirthDate { get; set; } }
3、实体配置类
class PersonEntityConfig:IEntityTypeConfiguration<Person>// 与Person实体类对应 { public void Configure(EntityTypeBuilder<Person> builder) { builder.ToTable("Persons");
builder.Property(t=>t.Name).HasMaxLength(200).IsRequired();//给Name设置最大长度,并且不为空 } }
4、创建DBContext类
public class TestDBContext:DbContext { public DbSet<Person> Persons; protect override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string connStr = "Server=.;DataBase=demo;Trusted_Connection=True;MuiltipleActiveResultSet=true"; optionsBuilder.UserSqlServer(connStr); } protect override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.AppConfigurationsFromAssembly(this.GetType().Assembly);//从当前程序集中加载所有的EntityTypeConfiguration } }
5、生成数据库
先安装Microsoft.EntityFrameworkCore.Tools,
然后在程序包管理器控制台中执行Add-Migration 此次迁移说明
然后在程序包管理器控制台中执行Update-Database
数据库中表创建成功
6、实体类有修改?
执行Add-Migration xxx,然后执行Update-Database
二、增删改查
1、增
using(var ctx =new TestDBContext()) { Person p = new Person(); p.Name = "111"; ctx.Persons.Add(p); await ctx.SaveChangesAsync(); }
2、删
using(var ctx =new TestDBContext()) { var p = ctx.Perons.Single(t=>t.Id==1); ctx.Perons.Remove(p); // ctx.Remove(p) await ctx.SaveChangesAsync(); }
3、改
using(var ctx =new TestDBContext()) { var p = ctx.Persons.Single(t=>t.Id==1); p.Name="djifjsd"; await ctx.SaveChangesAsync(); }
4、查
using(var ctx = new TestDBContext()) { var perons = ctx.Persons.Where(t=>t.Name=="111"); var persons1 = ctx.Perons.OrderBy(t=>t.Id); }
标签:基本,Core,set,Name,get,EF,ctx,var,public From: https://www.cnblogs.com/lixiang1998/p/17787656.html