Hi
I have implemented a simple repository pattern for the Entity Framework in a web app.
I have several repositories which all subclass a base which has some common methods in
The base looked like this
public class BaseRepository<TEntity> : IRepository<TEntity>
{
protected readonly RedirectsEntities Context;
public BaseRepository()
{
Context = new RedirectsEntities();
}
(RedirectsEntities is the EF datacontext, or whatever it's called)
And I had a RuleRepository and a SiteRepository which subclassed it
However, this caused me problems when looking up a site and using that value to save to a rule
the error was
"ADO.Net Entity Framework An entity object cannot be referenced by multiple instances of IEntityChangeTracker"
Presumably because each repository has a different instance of RedirectsEntities ?
So I found this question : http://stackoverflow.com/questions/694625/ado-net-entity-framework-an-entity-object-cannot-be-referenced-by-multiple-instan
which suggests moving the datacontext to a seperate class, holding it in a a static variable
e.g.
public class DataContext
{
private static RedirectsEntities _dbEntities;
public static RedirectsEntities DbEntities
{
get
{
if (_dbEntities == null)
{
_dbEntities = new RedirectsEntities();
}
return _dbEntities;
}
set { _dbEntities = value; }
}
}
and then my base repository constructor would look like this :
public BaseRepository()
{
Context = DataContext.DbEntities;
}
So this appears to have solved my problem, but I am concerned that the scope of RedirectsEntities is now incorrect.
Can anyone comment on this?