標籤:
這裡使用 MS SQLSERVER ,網上大多使用 SQLite
先來一個CodeFirst
建立項目
這裡我們選擇 ASP.NET Core Web Application (.NET Core)
這裡選擇web 應用程式,然後更改身分識別驗證 改為 不進行身分識別驗證
然後再包管理主控台裡執行下面兩條命令
引用 EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore
再引用 EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.SqlServer
建立實體
我們在項目添加一個 Models 檔案夾。
建立一個User.cs
public class User { public int Id { get; set; } public string UserName { get; set; } public string Password { get; set; } }
這裡我為了方便,繼續建立 DataContext.cs
public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<User> Users { get; set; } }建立資料庫
開啟 Startup.cs 在 ConfigureServices 下添加如下代碼:
public void ConfigureServices(IServiceCollection services) {
//這裡就是填寫資料庫的連結字串 var connection = "Data Source=.;Initial Catalog=EFCore;User ID=sa;Password=sa.123"; services.AddDbContext<DataContext>(options => options.UseSqlite(connection)); // Add framework services. services.AddMvc(); }
添加好以後,我們來安裝 Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
在檔案總管中找到這個項目,找到 project.json檔案
在 tools節點下 增加代碼
"Microsoft.EntityFrameworkCore.Tools": { "version": "1.0.0-preview1-final", "imports": [ "portable-net45+win8+dnxcore50", "portable-net45+win8" ] },
效果如
之後 開始建立資料庫 使用 dotnet ef 命令
先開啟cmd 視窗 ,跳轉到當前專案檔夾
輸入
dotnet ef migrations add MyFirstMigration
再輸入
dotnet ef database update
這樣資料庫就建立好了
注意如果 IIS-Express 在運行中,你會遇到錯誤
CS2012: Cannot open ‘MvcMovie/bin/Debug/netcoreapp1.0/MvcMovie.dll‘ for writing -- ‘The process cannot access the file
‘MvcMovie/bin/Debug/netcoreapp1.0/MvcMovie.dll‘
because it is being used by another process.‘
dotnet ef 命令
dotnet (.NET Core) 是 .NET 的跨平台實現。你可以在這裡瞭解它。
dotnet ef migrations add Initial 運行 Entity Framework .NET Core CLI 遷移命令並建立初始化遷移。參數 "Initial" 可以是任意值,但是通常用這個作為第一個(初始的) 資料庫遷移。這個操作建立了一個 *Data/Migrations/_Initial.cs* 檔案,這個檔案包含了添加(或刪除)Movie 表到資料庫的遷移命令。
dotnet ef database update dotnet ef database update 用我們剛剛建立的遷移來更新資料庫。
添加 UserController
public class UserController : Controller { private efcoredemoContext _context; public UserController(efcoredemoContext context) { _context = context; } // GET: /<controller>/ public IActionResult Index() { return View(_context.Users.ToList()); } }
添加 Index.cshtml
@model IEnumerable<EFCoreDemo.Models.User>@{ ViewBag.Title = "使用者";}<table class="table"> <tr> <th>Id</th> <th>使用者名稱</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Id) </td> <td> @Html.DisplayFor(modelItem => item.UserName) </td> </tr> }</table>
然後就可以運行啦
感謝 ASP.NET Core 開發 - Entity Framework (EF) Core
EF Core實踐 (使用MS SqlServer)