在 Mac OS X 上創建的 .NET 命令行程序訪問數據庫 (使用Entity Framework 7 )¶
警告
您當前查看的頁面是未經授權的轉載!
如果當前版本排版錯誤,請前往查看最新版本:http://www.cnblogs.com/qin-nz/p/aspnet5-console-using-entity-framework-on-mac-os.html
提示
更新時間:2016年01月20日。
安裝環境¶
首先,你需要安裝 ASP.NET Core 1.0,沒錯,即使你只是想運行個命令行程序。
然后使用 brew 來安裝 ICU (在coreclr下,需要這個來避免已知問題)
sudo brew install icu4c
安裝 .NET 版本管理器(DNVM)
curl -sSL \
https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh \
| DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh
安裝 .NET 運行環境(DNX),本文選擇coreclr版的運行時
dnvm upgrade -r coreclr
如果安裝有問題,請參考 在 Mac OS 上創建並運行 ASP.NET Core 1.0 網站 的第一部分
創建項目¶
這次我們手動創建一個項目,有關空項目需要包含的內容,可以參考 ASP.NET Core 1.0 入門——了解一個空項目
創建項目 project.json
¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
{
"dependencies": {
"EntityFramework.Sqlite": "7.0.0-rc1-final",
"EntityFramework.Commands": "7.0.0-rc1-final",
"Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final",
"System.Linq": "4.0.1-beta-23516"
},
"commands": {
"run": "ConsoleApp",
"ef": "EntityFramework.Commands"
},
"frameworks": {
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-beta-*"
}
}
}
}
|
第3,4行,我們引用了 Entity Framework 的 Sqlite 和 Commands ,Sqlite 用於訪問本地的Sqlite數據庫,而 Commands 幫我們進行代碼到數據庫設計的操作。
第8,9行,說明了我們可以使用 dnx
運行的命令;
當我們使用 dnx run
的時候,dnx 會找到名為 ConsoleApp
文件夾所包含的項目的 Main
函數來運行;
而當我們使用 dnx ef --help
的時候,dnx 運行 EntityFramework.Commands
並且把 --help
傳遞進去。
接下來還原 Nuget 包引用,也就是下載 dependencies
的內容。
dnu restore
創建程序入口點 Program.Main
¶
在相同目錄下創建 Program.cs
,添加如下內容:
using System;
namespace ConsoleApp
{
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
}
在 ConsoleApp 目錄運行 dnx run
驗證程序是否正確運行,運行 dnx ef
驗證EF安裝是否成功。
使用 EntityFramework 進行數據訪問¶
添加 Model
和 DbContext
¶
這里,我們需要創建 Model
和 DbContext
兩種類型。
DbContext 實際上就是將數據庫實例映射到 .NET 的一個對象,通過這個對象,可以訪問到數據庫的所有內容。
我們自己定義一個 BloggingContext
繼承自 DbContext
,我們給這個數據庫定義兩張表 Blogs
和 Posts
。 同時在代碼中指定我們使用的是Sqlite數據庫,並給出連接字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System.Collections.Generic;
using System.IO;
using Microsoft.Data.Entity;
using Microsoft.Extensions.PlatformAbstractions;
namespace ConsoleApp
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var path = PlatformServices.Default.Application.ApplicationBasePath;
optionsBuilder.UseSqlite("Filename=" + Path.Combine(path, "blog.db"));
}
}
}
|
將下面的代碼插入到第19行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public 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; }
}
|
注意這里,第3,12行,都是以類名+Id來命名的;此時, EntityFramework 會把這個識別為主鍵, EntityFramework 必須有主鍵才能正常工作。
這段代碼在執行數據庫遷移后得到的兩張表結構如下圖:


第16-17行,進行了一個 Blog <–> Post 的一對多映射。
創建數據訪問程序¶
將 Program.cs 修改為下面的樣子,注意我添加了第二行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System;
using System.Linq;
namespace ConsoleApp
{
public class Program
{
public static void Main()
{
using (var db = new BloggingContext())
{
db.Blogs.Add(
new Blog
{
Name = "qin-nz",
Url = "http://cnblogs.com/qin-nz",
Posts = new[]
{
new Post{Title="post-1"},
new Post{Title="post-2"}
}.ToList()
});
var count = db.SaveChanges();
Console.WriteLine("{0} 條記錄保存成功", count);
Console.WriteLine("數據庫中的記錄如下");
foreach (var blog in db.Blogs)
{
Console.WriteLine($"{blog.Name}({blog.Url})");
if (blog.Posts != null)
{
foreach (var post in blog.Posts)
{
Console.WriteLine($" {post.Title}");
}
}
}
}
}
}
}
|
注解
對 BloggingContext
對象的操作並不會修改數據庫,僅當使用 SaveChanges()
后才能同步到數據庫中。
創建數據庫¶
截至目前,我們只是完成了代碼的編寫,但是並沒有創建一個可以訪問的數據庫。 下面,我們使用 dnx ef
根據代碼生成數據庫。
生成數據庫創建腳本:
dnx ef migrations add MyFirstMigration
根據腳本創建(更新)數據庫文件:
dnx ef database update
在 Mac OS X 上創建的 .NET 命令行程序訪問數據庫 (使用Entity Framework 7 ) 由 勤奮的小孩 創作,采用 知識共享 署名-相同方式共享 4.0 國際 許可協議進行許可。
本許可協議授權之外的使用權限可以從 http://space.cnblogs.com/msg/send/qin-nz 處獲得。