EFCore入门建表,增删改查
安装两个NuGet:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
1.创建一个Book.cs文件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { public class Book { public long Id { get; set; } //主键 public string Title { get; set; } //标题 public DateTime PubTime { get; set; } //发布日期 public double Price { get; set; } //单价 public string AuthorName { get; set; } //作者 } }
2.创建一个配置Book.cs文件的BookConfig.cs文件,如果进行配置,也可不创建
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { public class BookConfig : IEntityTypeConfiguration<Book> { public void Configure(EntityTypeBuilder<Book> builder) { builder.ToTable("T-Books"); //设置 Book和那一个表对应 builder.Property(x => x.Title).HasMaxLength(50).IsRequired(); //IsRequired不能为空 //HasMaxLength最大长度 builder.Property(s=>s.AuthorName).HasMaxLength(20).IsRequired(); //IsRequired不能为空 //HasMaxLength最大长度 builder.Property(x => x.Name).HasColumnType("varchar(20)"); //HasColumnType指定数据类型 //修改其它属性作为主键(默认Id作为主键使用) //builder.HasKey(x => x.Price); //设置默认值 builder.Property(x => x.PubTime).HasDefaultValue(DateTime.Now); //设置唯一索引 builder.HasIndex(x => x.Title).IsUnique(); //设置符合索引 builder.HasIndex(x => new { x.Name, x.AuthorName }); } } }
3,自定义一个文件,我这点取名MyDbContext.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp2 { public class MyDbContext : DbContext { public MyDbContext(DbContextOptions<MyDbContext> options):base(options) { } public DbSet<Book> books { get; set; } //public DbSet<Person> persons { get; set; } //public DbSet<Dog> Dogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //从当前程序集里面加载所以的IEntityTypeConfiguration modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } } }
4. 在Program.cs文件中注册DBContext
builder.Services.AddDbContext<MyDbContext>(options => { var conn = builder.Configuration.GetValue<string>("SqlServerUrl"); options.UseSqlServer(conn); });
appsettings.json文件内容:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "SqlServerUrl": "你的数据库连接字符串", "AllowedHosts": "*" }
5. 在程序包管理器控制台输入
Add-Migration 此处自定义说明添加描述
举例: Add-Migration Init
Update-Database 更新到数据库
6.查询数据,插入数据
static void Main() { using (MyDbContext ctx = new MyDbContext()) { //向数据库插入数据 //Book book = new Book(); //book.Title = "标题2"; //book.Price = 23.00; //book.AuthorName = "作者名字5"; //book.PubTime = DateTime.Now; //ctx.books.Add(book); // 添加到Books逻辑表里面 //ctx.SaveChanges(); 保存,同步到数据库 //查询数据 var items = ctx.books.Where(m => m.Price >= 50); foreach (var item in items) { Console.WriteLine(item.Price); } var s = ctx.books.OrderBy(m => m.Price); foreach (var item in s) { Console.WriteLine(item.Price); } Console.ReadKey(); } }
6. 编辑数据,删除数据
//修改数据,删除数据 var b = ctx.books.Single(i => i.Id == 1); b.Title = "新标题1"; var d = ctx.books.Single(n=>n.Id == 8); ctx.books.Remove(d); ctx.SaveChanges();