I know that the DBContext represents a session (Unit-Of-Work and Repository) with the database, however I an unsure as to when I should have a different DBContext. Currently, I have a separate DBContext for each table with a single DBSet for each DBContext.
Something like this (Blogs and Posts are in the same database):
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
public class PostContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
I'm not sure why I had a separate DBContext. I think that it is a sample I followed that was like this. However, I recently found that I get an exception when trying to do queries involving both contexts:
The specified LINQ expression contains references to queries that are associated with different contexts.
So, it seems that the obvious solution is for a single DBContext and multiple DBSets:
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
Is there any guideline for when to use different DBContexts and the pros and cons of each approach?