.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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM