Skip to content

Instantly share code, notes, and snippets.

@char-1ee
Last active June 23, 2022 06:37
Show Gist options
  • Save char-1ee/59498cc7079ce07bfa2f0fb83bf2b5f3 to your computer and use it in GitHub Desktop.
Save char-1ee/59498cc7079ce07bfa2f0fb83bf2b5f3 to your computer and use it in GitHub Desktop.
A trial .NET Core console app that performs data access against a SQLite database using Entity Framework Core.

Steps

  • Prerequisites: Visual Studio 2019 version 16.3+ with .NET Core cross-platform development.
  • Install Entity Framework Core.
    Install-Package Microsoft.EntityFrameworkCore.Sqlite
  • Create the database after having Model.cs.
    Install-Package Microsoft.EntityFrameworkCore.Tools
    Add-Migration InitialCreate
    Update-Database
  • Debugging as a console app.

Insights

  • Software design: Context.
  • In EF Core, the DB context is constructed in a way of
    • Encapsulate data models as DbSet, to query and save instances of data entities.
    • Config DB (Path, Database, Strategy etc.), for example SQLite, in the constructor for each of the contexts created.
    • and then expose CRUD interfaces in DB context to developers of LINQ queires.
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public string DbPath { get; }
public BloggingContext()
{
var folder = Environment.SpecialFolder.LocalApplicationData;
var path = Environment.GetFolderPath(folder);
DbPath = System.IO.Path.Join(path, "blogging.db");
}
// Config the DB used for the context.
// The method is called for each instance of the context created.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={DbPath}");
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new();
}
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; }
}
using System;
using System.Linq;
using var db = new BloggingContext();
Console.WriteLine($"Database path: {db.DbPath}.");
// Create
Console.WriteLine("Inserting a new blog");
db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
db.SaveChanges();
// Read
Console.WriteLine("Querying for a blog");
var blog = db.Blogs
.OrderBy(b => b.BlogId)
.First();
// Update
Console.WriteLine("Updating the blog and adding a post");
blog.Url = "http://devblogs.microsoft.com/dotnet";
blog.Posts.Add( new Post { Title = "Hello World", Content = "Trails on EF Core"});
db.SaveChanges();
// Delete
Console.WriteLine("Delete the blog");
db.Remove(blog);
db.SaveChanges();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment