asp.net core EF 连接数据库进行交互
1. 安装包
Microsoft.EntityFrameworkCore
Micosoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFramerworkCore.Tools
安装
数据库提供商
https://docs.microsoft.com/en-us/ef/core/providers
2.配置DB上下文
using Microsoft.EntityFrameworkCore; namespace Webgentle.BookStore.Data { public class BookStoreContext : DbContext { public BookStoreContext(DbContextOptions<BookStoreContext> options) : base(options) { } public DbSet<Books> Books { get; set; } //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) //{ // optionsBuilder.UseSqlServer("Server=.;Database=BookStore;Integrated Security=True"); // base.OnConfiguring(optionsBuilder); //} } }
或者直接在Startup文件
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BookStoreContext>( options=>options.UseSqlServer("Server=.;Database=BookStore;Integrated Security=True")); services.AddControllersWithViews(); #if DEBUG services.AddRazorPages().AddRazorRuntimeCompilation(); #endif }
3. 使用实体类的数据库如何使用EF生成数据库、迁移
打开工具--》Nuge包管理--》程序包管理控制台
输入
get-help entityframework
Add-Migration init
生成了这两个文件
更新到数据库
update-database
如何还要更新添加的话
然后就在PM下 add-migration added2columns (它的意思是添加了两个新的列到数据库模型中)
然后再更新 update-database
4. 在数据库中插入数据
private readonly BookStoreContext _context = null; public BookRepository(BookStoreContext context) { _context = context; } public int AddNewBook(BookModel model) { var newBook = new Books() { Author= model.Author, CreatedOn = DateTime.UtcNow, Description= model.Description, Title= model.Title, TotalPages= model.TotalPages, UpdatedOn=DateTime.UtcNow }; _context.Books.Add(newBook); _context.SaveChanges(); return newBook.Id; }
[HttpPost] public ViewResult AddNewBook(BookModel bookModel) { _bookRepository.AddNewBook(bookModel); return View(); }
services.AddScoped<BookRepository, BookRepository>();
public BookController(BookRepository bookRepository) { _bookRepository=bookRepository; }
去页面提交
我们就成功添加了数据