Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
namespace ef_play
{
class Program
{
public class Blog
{
public string Id { get; set; }
public string Title { get; set; }
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=blogging.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>().HasAlternateKey(b => b.Title);
}
}
static void Main(string[] args)
{
string blogId = null;
using (var db = new BloggingContext()) {
db.Database.EnsureCreated();
var blog = new Blog {
Title = Guid.NewGuid().ToString()
};
db.Add(blog);
db.SaveChanges();
blogId = blog.Id;
Console.WriteLine($"Printing blog title for the first time: {blog.Title}");
}
using (var db = new BloggingContext()) {
var blog = new Blog {
Id = blogId,
Title = Guid.NewGuid().ToString()
};
db.Update(blog);
db.SaveChanges();
Console.WriteLine($"Printing blog title for the second time: {blog.Title}");
Console.WriteLine($"Printing original values: {db.Entry(blog).OriginalValues["Title"]}");
}
using (var db = new BloggingContext()) {
var blog = db.Blogs.FirstOrDefault(b => b.Id == blogId);
Console.WriteLine($"Printing blog title for the third time: {blog.Title}");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment