具有EntityFrameworkCore的ASP.NET Core中的SQLite [英] SQLite in ASP.NET Core with EntityFrameworkCore

查看:75
本文介绍了具有EntityFrameworkCore的ASP.NET Core中的SQLite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用EntityFramework 7在ASP.NET Core Web应用程序中添加和使用SQLite数据库?

How do you add and use an SQLite database in an ASP.NET Core web application, using EntityFramework 7 ?

当我听说它并创建了我的第一个Web应用程序时,便立即进入ASP.NET Core,突然间我想存储一堆数据,而SQLite似乎是显而易见的选择.
由于我希望它与我的应用程序一起使用,因此请使其保持轻巧,简单,并避免设置单独的数据库.

I dived into ASP.NET Core the moment I heard about it and created my first web application, I suddenly had a bunch of data that I wanted to store and SQLite seemed like the obvious choice.
Since I wanted it to stay with my application, keep it lightweight, simple and avoid setting up a separate database.

那么如何在ASP.NET Core中创建SQLite数据库呢?

So how would one go about creating an SQLite database in ASP.NET Core?

  • ASP.NET Core-现在以前称为ASP.NET MVC 6
  • EntityFramework核心-现在以前称为EntityFramework 7

推荐答案

更新:2016年11月4日.
重新格式化-图片转换为代码示例.
信息 :请记住,在某些代码示例中,省略了Visual Studio模板生成的代码.

Update: November 4th, 2016.
Reformatting - pictures to code examples.
Info: Keep in mind that in some code examples, code that was generated by the visual studio template have been omitted.

更新:2016年7月11日.
.NET Core和EntityFrameWork Core 1.0版即将发布!
因此,本指南值得稍作更新

Update: July 11th, 2016.
.NET Core and EntityFrameWork Core version 1.0 is upon us!
So this guide deserves a little update

第1步:
创建您的应用程序.

Step 1:
Create your application.

第2步:
获取必要的软件包
Microsoft.EntityFrameworkCore 1.0.0
Microsoft.EntityFrameworkCore.SQlite 1.0.0

Step 2:
Get the necessary packages
Microsoft.EntityFrameworkCore 1.0.0
Microsoft.EntityFrameworkCore.SQlite 1.0.0

第3步:
创建上下文:
(上下文将是您创建的类)

Step 3:
Create your context:
(The Context will be a class that you create)

public class DatabaseContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=MyDatabase.db");
    }
}

第4步:
将上下文添加到服务中:
(位于您的Startup类中)

Step 4:
Add your context to your services:
(Located in your Startup class)

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}

第5步:
在启动时通过将其添加到启动方法中来创建数据库
(位于启动"类中)

Step 5:
Create your database on startup, by adding it to the startup method
(Located in the Startup class)

public Startup(IHostingEnvironment env)
{
    using(var client = new DatabaseContext())
    {
        client.Database.EnsureCreated();
    }
}

EtVoíla!
现在,您将能够在ASP.NET Core应用程序中使用SQLite.
关于如何创建模型以及如何使用数据库上下文,旧指南仍然适用.

Et Voíla!
Now you will be able to use SQLite in your ASP.NET Core applications.
The old guide still applies regarding how you create your models as well as using your database context.

更新:2016年5月28日.
.NET Core RC2和EntityFramework Core RC1已发布.
他们改进并简化了设置SQLite的步骤.
但是由于Newtonsoft.Json库和NuGet错误,我遇到了一些麻烦,无法复制.

Update: May 28th, 2016.
.NET Core RC2 and EntityFramework Core RC1 have been released.
They have improved and simplified the steps for setting up SQLite.
But I'm experiencing some trouble with it and can't replicate it, because of an error with the Newtonsoft.Json library and NuGet.

如果您现在想这样做,我建议您坚持使用RC1库!

第1步:
创建您的ASP.NET Web应用程序

Step 1:
Create your ASP.NET web application

第2步:
转到工具-> Nuget数据包管理器->管理解决方案的Nuget程序包.
搜索 EntityFramework.SQLite 并选中 Include prelease 框.
安装软件包

Step 2:
Go to Tools -> Nuget Packet Manager -> Manage Nuget Packages for Solution.
Search for EntityFramework.SQLite and check the Include prelease box.
Install the package

第3步:创建上下文
为您的数据库创建一个上下文类.
随便什么都可以调用它,但让我们继续使用一些习惯,例如 MyDbContext .让您的新类继承DbContext类,并重写OnConfiguring方法并按如下方式定义您的连接:

Step 3: Creating a context
Create a context class for your database.
Call it whatever you want, but let's go with something that's customiary, like MyDbContext. Make your new class inherit the DbContext class and override the OnConfiguring method and define your connection like so:

public class MyDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "MyDb.db" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }
}

第4步:
转到 Startup.cs 并确保在Web应用程序的开始处创建了数据库:

Step 4:
Go to the Startup.cs and make sure your database is created at the start of your web application:

public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);         


        using (var db = new MyDbContext())
        {
            db.Database.EnsureCreated();
            db.Database.Migrate();
        }

    }

第二,我们需要添加服务:

Secondly we need to add the service:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        services.AddEntityFramework()
        .AddSqlite()
        .AddDbContext<MyDbContext>();
    }

第5步:定义模型
创建模型并转到 MyDbContext.cs 并为每个新模型添加一个新属性(假设您要为每个模型都有一个表!)
这是一个示例:
我的模特:

Step 5: Defining your Models
Create your models and go to MyDbContext.cs and add a new property for each of your new models (given that you want a table for each!)
Here's an example:
My Model:

public class Category
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public string UrlSlug { get; set; }
}

将其添加到我的上下文中:

Adding it to my context:

public class MyDbContext : DbContext
{
    public DbSet<Category> Categories { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "MyDb.db" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }
}

第6步:使用上下文
转到HomeController并向控制器添加一个新字段.
私有只读MyDbContext _myDbContext = new MyDbContext();
并将其传递给返回的视图,并在ActionResult中使用它:(现在假设我们在数据库中有一个类别)

public IActionResult Index()
{
    var category = _myDbContext.Categories.First();
    return View(category);
}

因此,通过进入索引视图,您可以使用数据库中的虚构数据.通过在视图顶部定义模型,如下所示:

So by going to your Index view, you can use our imaginary data from the database. By defining a model in the top of your view like so:

@model  MyNameSpace.Models.Category
@{
   ViewData["Title"] = "Hey Ho! SO!";
}


<div class="page-header">
    <h1>@ViewData["Title"]</h1>
</div>

<div class="container">
    @Model.Title
</div>

现在,通过启动我们的Web应用程序并转到分配的地址,我们应该看到一个带有花哨的引导程序标题的默认html页面,该页面在页面上显示:

Now by starting our web application and going to the assigned address we should see a default html page with a fancy bootstrap header, showing this on the page:

第二行是(或将是)数据库中第一类的标题.

The second line is (or would be) the title of our first category in our database.

实体框架7文档

这是我的第一个问答环节-如果您有任何意见或需要澄清的内容,请随时发表评论.
这是一个非常基本的示例,说明如何将SQLite数据库实现到ASP.NET Core MVC Web应用程序中.请注意,有几种方法可以设置数据库的连接字符串,如何使用上下文,并且EntityFramework 7仍是预发行版

这篇关于具有EntityFrameworkCore的ASP.NET Core中的SQLite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆