我在百度上搜了一下.net core和efcore 入門案例。好多博客都是大概說了一下做法,對於小白而言還是一頭霧水,我今天就抽出一點時間,寫一個詳細的入門小案例,就一張表沒有什么業務可言。主要是操作的步驟,當然這只是讓小白入個門,以后到公司工作,每個項目經理搭的架構不完全一樣,但是我們懂了基本的,再做項目架構稍微復雜的就能很快上手,因為底層原理大同小異。話不多說我們開始動手做吧。
- 為了我們后期更好打開項目我們新建一個項目解決方案這個你們隨意,咱們這個項目做
NETCOREDemo.
2.在解決方案下,打開VS2017新建項目,選擇ASP.NET Core Web應用程序
3. ASP.NET Core 的版本自己可以選擇,咱們這里選擇2.0。選擇空然后確定。
4.添加相關引用
有兩種方式
第一種采用命令行:這個我就不多說了,可以百度一下命令行安裝EFCore相關包(不同的數據庫包也不一樣,搜索的時候關鍵帶上自己的數據庫)
第二種簡單好用:我就以SQLSERVER數據庫為例,我們新建好的項目有個依賴項,我們右鍵>點擊NuGet程序包
5.點瀏覽搜索一.Microsoft.EntityFrameworkCore.SqlSerVer 二. Microsoft.EntityFrameworkCore.Tools 這兩個包然后安裝
6.添加好引用后,繼續設計數據庫,采用EFCore CodeFirst,我們先建立一個文件夾Models
在文件夾下添加這個類:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace MyNoteItem.Models { public class Note { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] // 主鍵自增id public int Id { get; set; } [Required] [MaxLength(100)] public string Title { get; set; } [Required] public string Content { get; set; } public DateTime Create { get;set; } } }
7.接着在Models下創建一個NoteContext繼承我們的上下文DbContext
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyNoteItem.Models { public class NoteContext:DbContext { public NoteContext(DbContextOptions<NoteContext> options) : base(options) { } public DbSet<Note> Notes { get; set; } } }
8.打開Startup.cs添加如下代碼,當然連接串因自己的數據庫用戶和密碼
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using MyNoteItem.Models; using MyNoteItem.Repository; namespace MyNoteItem { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var connection = @"Server=LAPTOP-OEENOHEO\LOCAL;DataBase=Note;UID=sa;PWD=sa123;"; services.AddDbContext<NoteContext>(options=>options.UseSqlServer(connection)); services.AddScoped<INoteRepository, NoteRepository>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseMvc(routes => //為程序注冊路由,默認打開的頁面 { routes.MapRoute( name: "default", template: "{controller=Note}/{action=Index}/{id?}"); }); } } }
9.單擊VS的菜單>工具>NuGet包管理器>程序包管理控制台,打開后在程序包管理器控制台執行如下命令:
Add-Migration NoteFirst
Update-Database
執行完出現Done表示 成功,查看數據庫,看是否生成對應的數據庫。如出現錯誤檢查一下數據庫連接串是否正確。EF Core 默認生成的表名為復數形式,可以在NoteContext的OnModelCreating方法改寫(具體可以百度)。
10.接下來項目一步步搭建,項目結構如下:
11.項目運行結果如下:
12.雖然是個入門demo,代碼量還是有的,所以我放在了我的GitHub上,供大家免費下載,地址如下:
https://github.com/LZYSW/.NetCoreDemo1.git
后續分頁等功能。讓我期待下一期的到來吧!希望對大家有用。