EF?Core基礎入門教程
EF Core 是一個ORM(對象關系映射),它使 .NET 開發(fā)人員可以使用 .NET對象操作數(shù)據(jù)庫,避免了像ADO.NET訪問數(shù)據(jù)庫的代碼,開發(fā)者只需要編寫對象即可。
EF Core 支持多種數(shù)據(jù)庫引擎:
- Microsoft SQL Sever
- SQLite
- Npgsql
- MySQL
- ......
1.獲取EF Core
通過NuGet獲取要使用的數(shù)據(jù)庫支持。比如:Microsoft SQL Sever
打開NuGet程序包管理器控制臺,輸入:Install-PackageMicrosoft.EntityFrameworkCore.SqlServer
2.模型
EF Core 是通過一個模型進行數(shù)據(jù)庫訪問的。模型由實體類和表示與數(shù)據(jù)庫中的會話組成的,以及允許你查詢和保存數(shù)據(jù)派生的上下文。
既可以從現(xiàn)有數(shù)據(jù)庫生成模型,也可以使用EF 遷移來完成從模型生成數(shù)據(jù)庫,也就是Database First 和 Code First。
簡單的模型:
public partial class TestContext : DbContext { public TestContext() { } public TestContext(DbContextOptions<TestContext> options) : base(options) { } public virtual DbSet<User> User { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=Test;Integrated Security=True"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) {} }
使用模型操作數(shù)據(jù)庫:
public class HomeController : Controller { private DataContext _context; public HomeController(DataContext context) { _context = context; } public IActionResult Index() { _context.User.Add(new User() { Name="name",Password="123"}); _context.SaveChanges(); //查詢 var users = _context.User.ToList(); return View(); }
3.Code First
Code First 也就是通過EF遷移來完成從模型生成數(shù)據(jù)庫。
1.創(chuàng)建項目
創(chuàng)建一個ASP.NET Core WEB 應用程序
2.打開NuGet包管理器下載Microsoft.EntityFrameworkCore.SqlServer 和Microsoft.EntityFrameworkCore.Tools
3.在Models文件夾創(chuàng)建實體類和上下文類
public class BlogContext:DbContext { public BlogContext(DbContextOptions<BlogContext> options) : base(options) { } public DbSet<Blog> Blog { get; set; } public DbSet<Post> Post { get; set; } }
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public virtual List<Post> Posts { get; set; } }
public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } }
4.在ConfigureServices方法中添加上下文依賴注入:
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); var connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<BlogContext>(options => options.UseSqlServer(connectionString)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
5.在appsettings.json中添加鏈接數(shù)據(jù)庫字符串
{ "ConnectionStrings": { "DefaultConnection": "Data Source=.;Initial Catalog=Blog;Integrated Security=True" }, "Logging": { "LogLevel": { "Default": "Information" } }, "AllowedHosts": "*" }
6.打開NuGet程序包管理控制臺,先輸入 Add-Migration FirstMigration,再輸入Update-Database。遷移成功后,會創(chuàng)建數(shù)據(jù)庫,以及會在項目中生成一個Migrations文件夾,里面時遷移記錄。
創(chuàng)建成功就可以通過構造函數(shù)依賴注入的方式訪問數(shù)據(jù)庫了。
4.Database First
Database First,也就是通過現(xiàn)有數(shù)據(jù)庫生成模型
1.創(chuàng)建項目,并安裝Microsoft.EntityFrameworkCore.SqlServer , Microsoft.EntityFrameworkCore.Tools 和Microsoft.EntityFrameworkCore.SqlServer.Design
2.在NuGet程序包管理器控制臺輸入:Scaffold-DbContext "Data Source=.;Initial Catalog=Blog;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer 。執(zhí)行成功會生成相關模型:
3,現(xiàn)在可以使用上下文訪問數(shù)據(jù)庫了,但是不能通過依賴注入的方式。如果需要,還是在ConfigureServices方法中添加代碼:services.AddDbContext<BlogContext>()。如果要使用appsettings.json中的連接字符串,就需要按照上面ConfigureServices方法中所寫的。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
.NET Core 2.0遷移小技巧之web.config 配置文件示例詳解
這篇文章主要給大家介紹了關于.NET Core 2.0遷移技巧之web.config 配置文件的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。2017-08-08ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解
本文詳細講解了ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09Redis數(shù)據(jù)庫基礎與ASP.NET?Core緩存實現(xiàn)
這篇文章介紹了Redis數(shù)據(jù)庫基礎與ASP.NET?Core緩存實現(xiàn)的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02.Net Core配置Configuration具體實現(xiàn)
這篇文章主要介紹了.Net Core配置Configuration具體實現(xiàn),文中運用大量代碼進行講解,如果有對相關知識感興趣的小伙伴可以參考這篇文章,希望可以幫助到你2021-09-09