I am just beginning to learn Entity Framework (starting with 5.0) and running into some issues. After watching a few videos on Pluralsight, I decided to get creative and created an abstract base class that inherited from DbContext and exposed a single “DataContext” property that was a DbSet of a generic type. Something like this:
public abstract class BaseDataContext<E> : DbContext
where E : CustomEntity
{
public DbSet<E> DataContext {get;set;}
public BaseDataContext()
{
Database.SetInitializer<BaseDataContext<E>>(null);
}
}
This seemed to be working great until I started dealing with entities that had relationships with each other (parent/child). What was occurring is when I tried to add a new child entity to the database via a data class that inherited BaseDataContext is instead of just attaching the reference (meaning, taking the child and say “your parent key is 123”), it created another record with a new key for the parent and all other fields duplicated and made this new record the parent of the child. I tried just setting the key property of my child (nulling out the property that was exposed with the data), but that didn’t change anything. I found a thread on SO (here) that said it wasn’t a good idea to do multiple data contexts like what I was attempting to do and seemed to explain exactly what was happening.
My question for this is, with the popularity EF seems to be gaining for everyone, is this the common approach? To create a single data context that is then passed around with constructors everywhere? Or is there a simpler way that is more common? This would especially apply if things get into background threads since passing a context there might get difficult.
Thanks in advance!
You get the most out of EF, as any tool, when you use as intended. So it’s good you ask. Entity Framework, especially code-first, is all about persistence ignorance (explained here for example). I don’t know what your comment “like you would’ve done before EF/L2S” refers to, but it sounds like active record. That’s not the way to go.
The context is responsible for materializing entities from the store, tracking changes and saving changes to the database. In more detail: the context manages the unit of work (tracking changes) and it’s
DbSetmembers serve as basic repositories (materializing and saving). The entity classes themselves know nothing about this. (As a side note: in theObjectContextAPI they do, but they can be coded against as persistence ignorant).Now about “multiple contexts”. The question you refer to is about multiple context instances of the same context type. Your question is about multiple context types (and, necessarily, multiple instances). Let’s sort this out:
So be as creative as you can, experiment as much as you can. Use EF as it is intended to and have lots of fun!