Skip to content

Instantly share code, notes, and snippets.

@deslee
Created December 19, 2018 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deslee/aa120aa4b73fbc6fb712c8011360da31 to your computer and use it in GitHub Desktop.
Save deslee/aa120aa4b73fbc6fb712c8011360da31 to your computer and use it in GitHub Desktop.
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