Search code examples
c#entity-frameworkentityloose-coupling

Loose coupling with entity framework


I'm trying to loosely couple this code, but I'm not sure how or if I should.

I'm using Entity Framework and DbContext is the inherited class used by the entity object TMeasure. When I run this code I'm getting this error:

'System.Data.Entity.DbContext' does not contain a definition for 'TMeasures' and no extension method 'TMeasures' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?)

Can someone help me with this?

Thanks!

class MeasureRepository: IMeasureRepository
{
    private DbContext db;

    public MeasureRepository(DbContext db)
    {
        this.db = db;
    }

    public List<TMeasure> GetAll()
    {
        var results = (from i in db.TMeasures
                        orderby i.strMeasure
                        select i).ToList();
        return results;
    }
}

Solution

  • You should create your own context:

    //Internal class recommended
    public class MeasuringContext : DbContext
    {
         public DbSet<Measure> Measures { get; set; }
    }
    

    And then use this context instead of the generic one:

    class MeasureRepository : IMeasureRepository
    {
        private MeasuringContext db;
    
        //...
    }