SQLite EF Core Database Provider

來源:互聯網
上載者:User

標籤:sys   soft   nuget   作業系統   sql   war   change   部分   tools   

原文連結

This database provider allows Entity Framework Core to be used with SQLite. The provider is maintained as part of the Entity Framework Core project.

 

Supported Database Engines
  • SQLite (3.7 onwards)
Supported Platforms
  • .NET Framework (4.5.1 onwards)

  • .NET Core

  • Mono (4.2.0 onwards)

  • Universal Windows Platform

 

Getting Started with EF Core on Universal Windows Platform (UWP) with a New Database

 

Getting Started with EF Core on .NET Core Console App with a New database

 

SQLite EF Core Database Provider Limitations

 

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

 

ASP.NET Core 開發 - Entity Framework (EF) Core

 

應用EF訪問SQLite資料

 

Entity Framework 文檔   &&  nuget

 

 

Testing with SQLite

 

SQLite has an in-memory mode that allows you to use SQLite to write tests against a relational database, without the overhead of actual database operations.

 

Example testing scenario

Consider the following service that allows application code to perform some operations related to blogs. Internally it uses a DbContext that connects to a SQL Server database. It would be useful to swap this context to connect to an in-memory SQLite database so that we can write efficient tests for this service without having to modify the code, or do a lot of work to create a test double of the context.

 

Get your context readyAvoid configuring two database providers

In your tests you are going to externally configure the context to use the InMemory provider. If you are configuring a database provider by overriding OnConfiguring in your context, then you need to add some conditional code to ensure that you only configure the database provider if one has not already been configured.

Tip

If you are using ASP.NET Core, then you should not need this code since your database provider is configured outside of the context (in Startup.cs).

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){    if (!optionsBuilder.IsConfigured)    {        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;ConnectRetryCount=0");    }}

  

Add a constructor for testing

The simplest way to enable testing against a different database is to modify your context to expose a constructor that accepts a DbContextOptions<TContext>.

public class BloggingContext : DbContext{    public BloggingContext()    { }    public BloggingContext(DbContextOptions<BloggingContext> options)        : base(options)    { }

  DbContextOptions<TContext> tells the context all of its settings, such as which database to connect to. This is the same object that is built by running the OnConfiguring method in your context.

Writing tests

The key to testing with this provider is the ability to tell the context to use SQLite, and control the scope of the in-memory database. The scope of the database is controlled by opening and closing the connection. The database is scoped to the duration that the connection is open. Typically you want a clean database for each test method.

using BusinessLogic;using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using Microsoft.VisualStudio.TestTools.UnitTesting;using System.Linq;namespace TestProject.SQLite{    [TestClass]    public class BlogServiceTests    {        [TestMethod]        public void Add_writes_to_database()        {            // In-memory database only exists while the connection is open            var connection = new SqliteConnection("DataSource=:memory:");            connection.Open();            try            {                var options = new DbContextOptionsBuilder<BloggingContext>()                    .UseSqlite(connection)                    .Options;                // Create the schema in the database                using (var context = new BloggingContext(options))                {                    context.Database.EnsureCreated();                }                // Run the test against one instance of the context                using (var context = new BloggingContext(options))                {                     var service = new BlogService(context);                    service.Add("http://sample.com");                }                // Use a separate instance of the context to verify correct data was saved to database                using (var context = new BloggingContext(options))                {                    Assert.AreEqual(1, context.Blogs.Count());                    Assert.AreEqual("http://sample.com", context.Blogs.Single().Url);                }            }            finally            {                connection.Close();            }        }        [TestMethod]        public void Find_searches_url()        {            // In-memory database only exists while the connection is open            var connection = new SqliteConnection("DataSource=:memory:");            connection.Open();            try            {                var options = new DbContextOptionsBuilder<BloggingContext>()                    .UseSqlite(connection)                    .Options;                // Create the schema in the database                using (var context = new BloggingContext(options))                {                    context.Database.EnsureCreated();                }                // Insert seed data into the database using one instance of the context                using (var context = new BloggingContext(options))                {                    context.Blogs.Add(new Blog { Url = "http://sample.com/cats" });                    context.Blogs.Add(new Blog { Url = "http://sample.com/catfish" });                    context.Blogs.Add(new Blog { Url = "http://sample.com/dogs" });                    context.SaveChanges();                }                // Use a clean instance of the context to run the test                using (var context = new BloggingContext(options))                {                    var service = new BlogService(context);                    var result = service.Find("cat");                    Assert.AreEqual(2, result.Count());                }            }            finally            {                connection.Close();            }        }    }}

  

 

 

SQLite,是一款輕型的資料庫,是遵守ACID的關係型資料庫管理系統,它包含在一個相對小的C庫中。它是D.RichardHipp建立的公有領域項目。它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它佔用資源非常的低,在嵌入式裝置中,可能只需要幾百K的記憶體就夠了。它能夠支援Windows/Linux/Unix等等主流的作業系統,同時能夠跟很多程式語言相結合,比如 Tcl、C#、PHP、Java等,還有ODBC介面,同樣比起Mysql、PostgreSQL這兩款開源的世界著名資料庫管理系統來講,它的處理速度比他們都快。SQLite第一個Alpha版本誕生於2000年5月。 至2015年已經有15個年頭,SQLite也迎來了一個版本 SQLite 3已經發布。

不像常見的客戶-伺服器範例,SQLite引擎不是個程式與之通訊的獨立進程,而是串連到程式中成為它的一個主要部分。所以主要的通訊協定是在程式設計語言內的直接API調用。這在消耗總量、延遲時間和整體簡單性上有積極的作用。整個資料庫(定義、表、索引和資料本身)都在宿主主機上儲存在一個單一的檔案中。它的簡單的設計是通過在開始一個事務的時候鎖定整個資料檔案而完成的。[1] 

 

 

SQLite 教程

SQLite 是一個軟體庫,實現了自給自足的、無伺服器的、零配置的、事務性的 SQL 資料庫引擎。SQLite 是在世界上最廣泛部署的 SQL 資料庫引擎。SQLite 原始碼不受著作權限制。

 

為什麼要用 SQLite?
  • 不需要一個單獨的伺服器處理序或操作的系統(無伺服器的)。

  • SQLite 不需要配置,這意味著不需要安裝或管理。

  • 一個完整的 SQLite 資料庫是儲存在一個單一的跨平台的磁碟檔案。

  • SQLite 是非常小的,是輕量級的,完全配置時小於 400KiB,省略可選功能配置時小於250KiB。

  • SQLite 是自給自足的,這意味著不需要任何外部的依賴。

  • SQLite 事務是完全相容 ACID 的,允許從多個進程或安全執行緒訪問。

  • SQLite 支援 SQL92(SQL2)標準的大多數查詢語言的功能。

  • SQLite 使用 ANSI-C 編寫的,並提供了簡單和便於使用的 API。

  • SQLite 可在 UNIX(Linux, Mac OS-X, Android, iOS)和 Windows(Win32, WinCE, WinRT)中運行。

 

目前 EF Core 支援的資料庫:

  • Microsoft SQL Server
  • SQLite
  • Postgres (Npgsql)
  • SQL Server Compact Edition
  • InMemory (for testing purposes)

後面將會增加:

  • MySQL
  • IBM DB2

 

SQLite EF Core Database Provider

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.