diff --git a/EFCore/EFCore.csproj b/EFCore/EFCore.csproj new file mode 100644 index 0000000..294a02c --- /dev/null +++ b/EFCore/EFCore.csproj @@ -0,0 +1,18 @@ + + + + Exe + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + diff --git a/EFCore/Model.cs b/EFCore/Model.cs new file mode 100644 index 0000000..941cc8c --- /dev/null +++ b/EFCore/Model.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore; + +public class BloggingContext : DbContext +{ + public DbSet? Blogs { get; set; } + public DbSet? Posts { get; set; } + + + // The following configures EF to create a Sqlite database file in the + // special "local" folder for your platform. + protected override void OnConfiguring(DbContextOptionsBuilder options) + => options.UseNpgsql("User ID=postgres;Password=1234;" + + "Host=localhost;Port=5432;Database=staracademy;" + + "Connection Lifetime=0;"); +} + +public class Blog +{ + public string BlogId { get; set; } + public string? Url { get; set; } + + public List? Posts { get; } = new(); +} + +public class Post +{ + + public string PostId { get; set; } + public string? Title { get; set; } + public string? Content { get; set; } + + public int BlogId { get; set; } + public Blog? Blog { get; set; } +} \ No newline at end of file diff --git a/EFCore/Program.cs b/EFCore/Program.cs new file mode 100644 index 0000000..700f483 --- /dev/null +++ b/EFCore/Program.cs @@ -0,0 +1,35 @@ +using var db = new BloggingContext(); + +// Create +Console.WriteLine("Inserting a new blog"); +Blog firstBlog = new Blog +{ + BlogId = Guid.NewGuid().ToString(), + Url = "http://blogs.msdn.com/adonet" +}; + +db.Add(firstBlog); +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 = "https://devblogs.microsoft.com/dotnet"; +Post post = new Post +{ + Title = "Hello World", + Content = "I wrote an app using EF Core!", + PostId = Guid.NewGuid().ToString(), +}; +blog.Posts!.Add(post); +db.SaveChanges(); + +// Delete +Console.WriteLine("Delete the blog"); +db.Remove(blog); +db.SaveChanges(); \ No newline at end of file diff --git a/Folder.DotSettings.user b/Folder.DotSettings.user index 9048703..d9e238e 100644 --- a/Folder.DotSettings.user +++ b/Folder.DotSettings.user @@ -5,6 +5,6 @@ ForceIncluded INFO - C:\Users\m.shahmoradi\AppData\Local\JetBrains\Rider2023.3\resharper-host\temp\Rider\vAny\CoverageData\_Fall1402-MahdiShahMoradi.19\Snapshot\snapshot.utdcvr + \ No newline at end of file