The Entity Framework Core (hereinafter referred to as "EF core") supports multiple databases. In this article, we'll look at how to create a SQLite database using EF Core's code first method
Download SQLite, unzip will get three files, put in the C:\sqlite directory
Let's start by creating a. NET Core Console Program
Add the EF Core for SQLite component library
"Dependencies": { "Microsoft.EntityFrameworkCore.Sqlite": "1.1.0", "Microsoft.NETCore.App": { " Type ":" Platform ", " version ":" 1.0.0 " }},
Let's create a class that corresponds to a table in SQLite
Public class category{ publicintgetset;} Public string Get Set ; }}
In accordance with international practice we need to derive a class from DbContext (database context)
Public classSampledbcontext:dbcontext {Private Static BOOL_created =false; PublicSampledbcontext () {if(!_created) {_created=true; Database.ensuredeleted (); Database.ensurecreated (); } } protected Override voidonmodelcreating (ModelBuilder ModelBuilder) {Base. Onmodelcreating (ModelBuilder); Modelbuilder.entity<Category> (). ToTable ("tb_category"); } protected Override voidonconfiguring (Dbcontextoptionsbuilder optionbuilder) {Optionbuilder. Usesqlite (@"Data source=c:\sqlite\sqlitedb.db"); } }
Now let's add some data, open the Main method, add the following code
using(varDbContext =NewSampledbcontext ()) {Dbcontext.set<Category> (). ADD (NewCategory {Name ="Wigs" }); Dbcontext.set<Category> (). ADD (NewCategory {Name ="Shoes" }); Dbcontext.set<Category> (). ADD (NewCategory {Name ="Dresses" }); Dbcontext.savechanges (); foreach(varCatinchDbcontext.set<category>(). ToList ()) {Console.WriteLine ($"categoryid= {cat. Id}, CategoryName = {cat. Name}"); }} console.readkey ();
This time will create a database file under C:\sqlite sqlitedb.db, you can open the SQLite tool db Browser for SQLite
This example is actually very simple.
Create a SQLite database using the entity Framework Core Code First