勤奋的小孩

导航

在 Mac OS X 上创建的 .NET 命令行程序访问数据库 (使用Entity Framework 7 )

在 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 入门——了解一个空项目

创建项目文件夹

mkdir ConsoleApp
cd ConsoleApp

注解

请务必将文件夹命名为 ConsoleApp ,或者你需要更改后面 project.jsonrun 命令。

创建项目 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 进行数据访问

添加 ModelDbContext

这里,我们需要创建 ModelDbContext 两种类型。

DbContext 实际上就是将数据库实例映射到 .NET 的一个对象,通过这个对象,可以访问到数据库的所有内容。

我们自己定义一个 BloggingContext 继承自 DbContext ,我们给这个数据库定义两张表 BlogsPosts 。 同时在代码中指定我们使用的是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 必须有主键才能正常工作。

这段代码在执行数据库迁移后得到的两张表结构如下图:

https://qinblog.blob.core.windows.net/images/ef-console-blog-design.png https://qinblog.blob.core.windows.net/images/ef-console-post-design.png

第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

运行命令行程序

dnx run

如果项目没有错误,那么你应该看到下面的输出。

https://qinblog.blob.core.windows.net/images/ef-console-result-on-mac.png

至此,你已经成功的在 Mac OSX 上运行了一个 .NET 的命令行程序, 并对本地的数据库进行了读写访问。

声明 知识共享许可协议

在 Mac OS X 上创建的 .NET 命令行程序访问数据库 (使用Entity Framework 7 )勤奋的小孩 创作,采用 知识共享 署名-相同方式共享 4.0 国际 许可协议进行许可。
本许可协议授权之外的使用权限可以从 http://space.cnblogs.com/msg/send/qin-nz 处获得。

posted on 2015-12-15 16:34  勤奋的小孩  阅读(1962)  评论(2编辑  收藏  举报