3

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;
    }
}
2
  • I can't see in what way this could be considered "loosely coupled", it just seems broken. What is your end goal here? Do you want to write a repo that work with any DbContext rather than a specific class that derives from DbContext. If so google for "generic repository", i Know I have posted an example in the past. Oct 28, 2014 at 16:27
  • Mati (below) gave me a solution to my problem. It was obviously broken, but I'm talking about not having to instantiate a Entity class within the class. I'd rather pass the entity object to the class itself.
    – J Hunt
    Oct 29, 2014 at 14:31

1 Answer 1

2

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;

    //...
}
2
  • I guess this will allow me to change the context that the MeasureRepository class is receiving, if needed in the future?
    – J Hunt
    Oct 28, 2014 at 16:49
  • If what you want is a generic context, then this question may be helpful: Generic access to DbContext Oct 28, 2014 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.