using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
public int BlogId { get; set; }
public string Url { get; set; }
public string Id {get;set;}
public string Content {get;set;}
public List<PostTag> PostTags {get;set;}
public string Id {get;set;}
public string Name {get;set;}
public List<PostTag> PostTags {get;set;}
public string PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
public class BloggingContext : DbContext
public BloggingContext(){ }
public BloggingContext(DbContextOptions<BloggingContext> options)
protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<PostTag>()
.HasKey(x => new { x.PostId, x.TagId });
builder.Entity<PostTag>()
.WithMany(s => s.PostTags)
.HasForeignKey(st => st.PostId);
builder.Entity<PostTag>()
.WithMany(s => s.PostTags)
.HasForeignKey(st => st.TagId);
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<PostTag> PostTags { get; set; }
private BloggingContext _context;
public BlogService(BloggingContext context)
_context.Posts.Add(new Post(){ Id="1", Content="1" });
_context.Tags.Add(new Tag(){ Id="1", Name="1" });
_context.PostTags.Add(new PostTag(){ PostId="1", TagId="1" });
var postsQuery = _context.PostTags
.Where(st => st.TagId == "1")
var postsWithExtraData = postsQuery
.Include(s => s.PostTags)
.ThenInclude(st => st.Tag)
.OrderByDescending(s => s.Id)
Console.WriteLine("Tag Name = " + postsWithExtraData.First().PostTags.First().Tag.Name.ToString());
static void Main(string[] args)
Console.WriteLine("This is an example of using EF Core InMemory Database");
Console.WriteLine("======================================================");
var options = new DbContextOptionsBuilder<BloggingContext>()
.UseInMemoryDatabase(databaseName: "Add_writes_to_database")
using (var context = new BloggingContext(options))
var service = new BlogService(context);