Created
December 19, 2018 01:47
-
-
Save deslee/aa120aa4b73fbc6fb712c8011360da31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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