EF?Core基礎(chǔ)入門教程
EF Core 是一個(gè)ORM(對(duì)象關(guān)系映射),它使 .NET 開發(fā)人員可以使用 .NET對(duì)象操作數(shù)據(jù)庫,避免了像ADO.NET訪問數(shù)據(jù)庫的代碼,開發(fā)者只需要編寫對(duì)象即可。
EF Core 支持多種數(shù)據(jù)庫引擎:
- Microsoft SQL Sever
- SQLite
- Npgsql
- MySQL
- ......
1.獲取EF Core
通過NuGet獲取要使用的數(shù)據(jù)庫支持。比如:Microsoft SQL Sever
打開NuGet程序包管理器控制臺(tái),輸入:Install-PackageMicrosoft.EntityFrameworkCore.SqlServer
2.模型
EF Core 是通過一個(gè)模型進(jìn)行數(shù)據(jù)庫訪問的。模型由實(shí)體類和表示與數(shù)據(jù)庫中的會(huì)話組成的,以及允許你查詢和保存數(shù)據(jù)派生的上下文。
既可以從現(xiàn)有數(shù)據(jù)庫生成模型,也可以使用EF 遷移來完成從模型生成數(shù)據(jù)庫,也就是Database First 和 Code First。
簡(jiǎn)單的模型:
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)建項(xiàng)目
創(chuàng)建一個(gè)ASP.NET Core WEB 應(yīng)用程序

2.打開NuGet包管理器下載Microsoft.EntityFrameworkCore.SqlServer 和Microsoft.EntityFrameworkCore.Tools

3.在Models文件夾創(chuàng)建實(shí)體類和上下文類
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程序包管理控制臺(tái),先輸入 Add-Migration FirstMigration,再輸入U(xiǎn)pdate-Database。遷移成功后,會(huì)創(chuàng)建數(shù)據(jù)庫,以及會(huì)在項(xiàng)目中生成一個(gè)Migrations文件夾,里面時(shí)遷移記錄。

創(chuàng)建成功就可以通過構(gòu)造函數(shù)依賴注入的方式訪問數(shù)據(jù)庫了。
4.Database First
Database First,也就是通過現(xiàn)有數(shù)據(jù)庫生成模型
1.創(chuàng)建項(xiàng)目,并安裝Microsoft.EntityFrameworkCore.SqlServer , Microsoft.EntityFrameworkCore.Tools 和Microsoft.EntityFrameworkCore.SqlServer.Design
2.在NuGet程序包管理器控制臺(tái)輸入:Scaffold-DbContext "Data Source=.;Initial Catalog=Blog;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer 。執(zhí)行成功會(huì)生成相關(guān)模型:

3,現(xiàn)在可以使用上下文訪問數(shù)據(jù)庫了,但是不能通過依賴注入的方式。如果需要,還是在ConfigureServices方法中添加代碼:services.AddDbContext<BlogContext>()。如果要使用appsettings.json中的連接字符串,就需要按照上面ConfigureServices方法中所寫的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Visual Studio for Mac版 初體驗(yàn)
這篇文章主要介紹了Visual Studio for Mac版 初體驗(yàn),本文圖文并茂給大家介紹的非常詳細(xì),需要的朋友可以參考下2017-05-05
python scrapy項(xiàng)目下spiders內(nèi)多個(gè)爬蟲同時(shí)運(yùn)行的實(shí)現(xiàn)
這篇文章主要介紹了python scrapy項(xiàng)目下spiders內(nèi)多個(gè)爬蟲同時(shí)運(yùn)行的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
asp.net 光棒效應(yīng)實(shí)現(xiàn)代碼
asp.net 光棒效應(yīng)(今天剛剛學(xué)到的)2009-12-12
Extjs4.1.x 框架搭建 采用Application動(dòng)態(tài)按需加載MVC各模塊完美實(shí)現(xiàn)
中午的時(shí)候發(fā)了第一篇 Extjs4.1.x 框架搭建 采用Application動(dòng)態(tài)按需加載MVC各模塊,發(fā)現(xiàn)實(shí)現(xiàn)上還是有問題,本文將提供詳細(xì)的完美方案2012-11-11
Math.NET?Numerics?開源數(shù)學(xué)庫安裝使用詳解
本文給大家分享Math.NETNumerics庫的安裝方法和使用示例,該庫是C#中進(jìn)行科學(xué)計(jì)算和數(shù)據(jù)分析的常用工具,本文介紹實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-03-03
C# 獲取當(dāng)前星期幾三種實(shí)現(xiàn)方法
獲取當(dāng)前星期幾實(shí)現(xiàn)這個(gè)功能有多種方法,接下來將列出3種供你參考,感興趣的你可不要錯(cuò)過了哈,希望本文所提供的知識(shí)點(diǎn)對(duì)你有所幫助2013-02-02
asp.net后臺(tái)關(guān)閉當(dāng)前頁面并傳值的兩種方法
這篇文章介紹了asp.net后臺(tái)關(guān)閉當(dāng)前頁面并傳值的兩種方法,有需要的朋友可以參考一下2013-10-10
ASP.NET導(dǎo)出Excel打開時(shí)提示:與文件擴(kuò)展名指定文件不一致解決方法
ASP.NET導(dǎo)出Excel,打開時(shí)提示“您嘗試打開文件'XXX.xls'的格式與文件擴(kuò)展名指定文件不一致” 很是郁悶,于是搜集了一些解決方法,感興趣的朋友可以了解下2013-01-01

