using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
public int BlogId { get; set; }
public string Url { get; set; }
public int? PrimaryThingId { get; set; }
public virtual Thing PrimaryThing {get; set;}
public virtual ICollection<BlogThing> BlogThings { get; set; }
PrimaryBlogs = new HashSet<Blog>();
BlogThings = new HashSet<BlogThing>();
public int ThingId { get; set; }
public ICollection<Blog> PrimaryBlogs {get; set;}
public virtual ICollection<BlogThing> BlogThings {get; set;}
public int BlogThingId {get; set;}
public int? BlogId {get; set;}
public int? ThingId {get; set;}
public virtual Blog Blog { get; set; }
public virtual Thing Thing { get; set; }
public class BloggingContext : DbContext
public BloggingContext(){ }
public BloggingContext(DbContextOptions<BloggingContext> options)
public DbSet<Blog> Blogs { get; set; }
public DbSet<Thing> Things {get; set;}
public DbSet<BlogThing> BlogThings {get; set;}
protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<Blog>().HasMany(x => x.BlogThings).WithOne(x => x.Blog);
modelBuilder.Entity<Blog>().HasOne(x => x.PrimaryThing).WithMany(x => x.PrimaryBlogs);
modelBuilder.Entity<Thing>().HasMany(x => x.BlogThings).WithOne(x => x.Thing);
modelBuilder.Entity<Thing>().HasMany(x => x.PrimaryBlogs).WithOne(x => x.PrimaryThing);
modelBuilder.Entity<BlogThing>().HasOne(x => x.Blog).WithMany(x => x.BlogThings);
modelBuilder.Entity<BlogThing>().HasOne(x => x.Thing).WithMany(x => x.BlogThings);
private BloggingContext _context;
public BlogService(BloggingContext context)
public void Add(string url)
var blog = new Blog { Url = url };
_context.Blogs.Add(blog);
public IEnumerable<Blog> Find(string term)
.Where(b => b.Url.Contains(term))
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);
Console.WriteLine("Adding new blog");
var primarything = new Thing
var secondarything = new Thing
var blogthing = new BlogThing
context.Things.Add(primarything);
context.Things.Add(secondarything);
context.BlogThings.Add(blogthing);
using (var context = new BloggingContext(options))
var things = context.Things
.Include(x => x.BlogThings)
.ThenInclude(x => x.Blog)
.Include(x => x.PrimaryBlogs)
.Where(x => x.BlogThings.Any(y => y.Blog.BlogId == 1) || x.PrimaryBlogs.Any(y => y.BlogId == 1))
Console.WriteLine($"Blogs things: {things.Count()}");