1- using System ;
1+ using Microsoft . EntityFrameworkCore ;
2+ using Microsoft . Extensions . DependencyInjection ;
3+ using Microsoft . Extensions . Hosting ;
4+ using System ;
25using System . Linq ;
36using 亂七八糟 . DataAccessLayer ;
47
@@ -12,33 +15,43 @@ public class Program
1215 /// <param name="args"></param>
1316 public static async Task Main ( string [ ] args )
1417 {
15- await using var db = new BloggingContext ( ) ;
16-
17- // Note: This sample requires the database to be created before running.
18- Console . WriteLine ( $ "Database path: { db . DbPath } .") ;
19-
20- // Create
21- Console . WriteLine ( "Inserting a new blog" ) ;
22- db . Add ( new Blog { Url = "http://blogs.msdn.com/adonet" } ) ;
23- db . SaveChanges ( ) ;
24-
25- // Read
26- Console . WriteLine ( "Querying for a blog" ) ;
27- var blog = db . Blogs
28- . OrderBy ( b => b . BlogId )
29- . First ( ) ;
30-
31- // Update
32- Console . WriteLine ( "Updating the blog and adding a post" ) ;
33- blog . Url = "https://devblogs.microsoft.com/dotnet" ;
34- blog . Posts . Add (
35- new Post { Title = "Hello World" , Content = "I wrote an app using EF Core!" } ) ;
36- db . SaveChanges ( ) ;
37-
38- // Delete
39- Console . WriteLine ( "Delete the blog" ) ;
40- db . Remove ( blog ) ;
41- db . SaveChanges ( ) ;
42-
18+ var host = Host . CreateDefaultBuilder ( args )
19+ . ConfigureServices ( services =>
20+ {
21+ services . AddDbContext < BloggingContext > ( options =>
22+ options . UseSqlite ( "Data Source=blogging.db" ) ) ;
23+ } ) . Build ( ) ;
24+
25+ using ( var scope = host . Services . CreateScope ( ) )
26+ {
27+ await using var db = new BloggingContext ( ) ;
28+ db . Database . EnsureCreated ( ) ;
29+
30+ // Note: This sample requires the database to be created before running.
31+ Console . WriteLine ( $ "Database path: { db . DbPath } .") ;
32+
33+ // Create
34+ Console . WriteLine ( "Inserting a new blog" ) ;
35+ db . Add ( new Blog { Url = "http://blogs.msdn.com/adonet" } ) ;
36+ db . SaveChanges ( ) ;
37+
38+ // Read
39+ Console . WriteLine ( "Querying for a blog" ) ;
40+ var blog = db . Blogs
41+ . OrderBy ( b => b . BlogId )
42+ . First ( ) ;
43+
44+ // Update
45+ Console . WriteLine ( "Updating the blog and adding a post" ) ;
46+ blog . Url = "https://devblogs.microsoft.com/dotnet" ;
47+ blog . Posts . Add (
48+ new Post { Title = "Hello World" , Content = "I wrote an app using EF Core!" } ) ;
49+ db . SaveChanges ( ) ;
50+
51+ // Delete
52+ Console . WriteLine ( "Delete the blog" ) ;
53+ db . Remove ( blog ) ;
54+ db . SaveChanges ( ) ;
55+ }
4356 }
4457}
0 commit comments