EF Core with SQLite in VS2017

This post is about using Entity Framework Core to access SQLite database in Visual Studio 2017. I will demonstrate the Database First approach.

 

FIRST, Install the following Nuget packages in your project:

  1. “Microsoft.EntityFrameworkCore.SQLite” (SQLite provider)
  2. “Microsoft.EntityFrameworkCore.Tools” (including”Scaffold-DbContext” and other db commands)
  3. “Microsoft.EntityFrameworkCore.Sqlite.Design” (the “Scaffold-DbContext” need this to generate class for SQLite database)

 

SECOND, Open “Nuget Package Manager Console”. Type the following command

<pre>

Scaffold-DbContext "Datasource=C:\ASPNET\APIApp\webbookmarks.db3" Microsoft.EntityFrameworkCore.SQLite -OutputDir Models

</pre>

After that you should find a XXXContext.cs and other class files representing your data model in the project folder.

 

THIRD, Then add these class files to your project using “Add Existing Items…” in your project menu.

Please note that your database connection string input in the Scaffold-DbContext command will be hard-coded in the datacontext.cs file as follows:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlite(@"Datasource=C:\Users\bliss\Desktop\bible web\biblebliss\bible.db");
}

 

Finally, you can use use the following code to access the SQLite database:


var = new dbcontext();

var versionshortnames = db.Version.Select(v => v.VersionShort).AsEnumerable();

 

References:

https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SQLite/
https://docs.microsoft.com/en-us/ef/core/providers/sqlite/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s