.Net Core EF Core之Sqlite使用及部署

1、添加引用Nuget包

Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Tools.DotNet

2、创建数据库上下文

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace ConsoleApp.SQLite
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=blogging.db");
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { 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; }
    }
}

Startup里注入:

services.AddDbContext<BloggingContext>();

3、数据库迁移

dotnet ef migrations add InitialCreate
//提交到数据库
dotnet ef database update

4、发布

这里仅说一下注意事项,我们在开发调试的时候,默认生成的数据库文件所在目录为:

bin/Debug/netcoreapp1.1/blogging.db

发布后,应该把数据库文件拷贝到发布程序的根目录里,不然报错,找不到数据库文件。

 

参考文献:https://docs.microsoft.com/zh-cn/ef/core/get-started/netcore/new-db-sqlite

文章出处:http://www.cnblogs.com/anech/p/6873385.html

    原文作者:sqlite
    原文地址: https://www.cnblogs.com/anech/p/6873385.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞