第一步、引入包
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.9" />
引入下面Tools这个包,这个包中包含Design这个包
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.9">
第二步、创建实体类
namespace LcyEfDemo.Core.Models
{
public class Book
{
public int Id { get; set; }
public string? Title { get; set; }
public string? Email { get; set; }
public DateTime? Created { get; set; }
}
}
第三步、创建实体配置类
这个类可以不创建,但是创建这个类感觉要清晰些,就不用全部写在DbContext类中去了,这就是FluentAPI。这里面可以对实体类进行配置,对应数据库
using LcyEfDemo.Core.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace LcyEfDemo.Core.ModelsConfig
{
public class BookConfig : IEntityTypeConfiguration<Book>
{
public void Configure(EntityTypeBuilder<Book> builder)
{
// builder.ToTable("T_Books");
builder.Property(b => b.Title).HasMaxLength(50).IsRequired().IsUnicode();
// 创建索引 index
builder.HasIndex(b => b.Title);
// IsUnique唯一索引,IsClustered聚集索引
builder.HasIndex(b => b.Email).IsUnique();
}
}
}
第四步、创建继承自DbContext的类
using LcyEfDemo.Core.Models;
using Microsoft.EntityFrameworkCore;
namespace LcyEfDemo.Core
{
public class AppDbContext : DbContext
{
public AppDbContext()
{
}
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Book> T_Books { get; set; }
public DbSet<Article> T_Article { get; set; }
public DbSet<Comment> T_Comment { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("server=.;database=TestDB;uid=sa;pwd=111111");
}
// 提高程序性能,取消全局跟踪.这个的意思就是必须呈上update delete等操作数据库的命令才会对数据库进行操作
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 下面这个代码以上就是,加载这个程序集中的所有config类
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
}
}
第五步、修改appsettings.json和Program.cs
在appsettings.json中添加数据库连接信息:
"ConnectionStrings": {
"Default": "server=.;database=TestDB;uid=sa;pwd=111111"
}
在Program.cs中添加DbContext继承的类,并添加数据库连接:
var configuration = builder.Configuration;
builder.Services.AddDbContext<AppDbContext>(option =>
{
option.UseSqlServer(configuration.GetConnectionString("Default"));
});
生成一次迁移
程序包管理器控制台执行以下代码,InitialCreate这个代表自己创建的迁移名字,名字尽量和用途一次
PM>Add-Migration InitialCreate创建迁移文件
PM>Update-database更新数据库
需要安装的命名工具dotnet tool install -g dotnet-ef
liunx > dotnet ef migrations add init
liunx > dotnet ef database update
反向迁移
dotnet ef dbcontext scaffold "server=.;database=DealerPlatform;uid=sa;pwd=111111" "Microsoft.EntityFrameworkCore.SqlServer" -o 文件夹名称
如果没有数据库,这里就会自动创建一个数据库,并且创建相应的表
增删改查数据方法
using LcyEfDemo.Core;
using LcyEfDemo.Core.Models;
using LcyEfDemo.System.IServices;
using Microsoft.EntityFrameworkCore;
namespace LcyEfDemo.System.Services
{
public class BookRepository : IBookRepository
{
private readonly AppDbContext _dbContext;
public BookRepository(AppDbContext dbContext)
{
this._dbContext = dbContext;
}
public async Task<Book> AddBookAsync(string? bookTitle, string? bookEmail, DateTime? bookTime)
{
Book book = new Book();
book.Title = bookTitle;
book.Email = bookEmail;
if (bookTime == null)
{
book.Created = DateTime.Now;
}
else
{
book.Created = (DateTime)bookTime;
}
await _dbContext.T_Books.AddAsync(book);
await _dbContext.SaveChangesAsync();
return book;
}
public async Task<Book> GetBookAsync(int bookId)
{
return await _dbContext.T_Books.FirstOrDefaultAsync(m => m.Id == bookId);
}
public async Task<IEnumerable<Book>> GetBooksAsync()
{
return await _dbContext.T_Books.ToListAsync();
}
public async Task<Book> UpdateBook(Book book)
{
Book singbook = await _dbContext.T_Books.SingleOrDefaultAsync(b => b.Id == book.Id);
singbook.Id = book.Id != 0 ? book.Id : singbook.Id;
singbook.Title = book.Title ??= singbook.Title;
singbook.Email = book.Email ??= singbook.Email;
singbook.Created = book.Created != null ? book.Created : singbook.Created;
_dbContext.T_Books.Update(singbook);
await _dbContext.SaveChangesAsync();
return singbook;
}
public async Task<int> Delete(int bookid)
{
var book = await _dbContext.T_Books.SingleOrDefaultAsync(s => s.Id == bookid);
_dbContext.T_Books.Remove(book);
return await _dbContext.SaveChangesAsync();
}
}
}