0

I have a simple database with a 'Person' and a 'Subscription' table where each person has one or more subscriptions.

    private MyDBContext_dbContext;       

    public T GetByID(int ID)
    {
        return _dbContext.Mapping. ??
    }

Now the intention was to create a generic method to return either a Person entity or a Subscription entity from the datacontext based on the type provided.

In Linq2SQL I was able to use .GetTable<T> method, how can I do the same here with EntityFramework 6? The .Mapping part isn't even recognized by intellisense, so i am missing something basic here.

Thanks

iAteABug_And_iLiked_it
  • 3,725
  • 9
  • 36
  • 75
  • I'm not sure if this will help, but EF's DatabaseContext is different than previous ObjectContext's, however you can access the object context like so and perhaps find familiar ground: http://stackoverflow.com/a/8084807/84206 – AaronLS Jun 03 '14 at 21:01
  • 1
    http://www.itworld.com/development/409087/generic-repository-net-entity-framework-6-async-operations This article discusses Generic Repository Pattern. Please consider pros and cons very carefully. If you application is big and has a long life-cycle with many updates and changes down the road, a generic repo may not be a good idea. – Roman Mik Jun 03 '14 at 21:12
  • +1 @rommik Oh this article is great - thanks , why might it not be a great idea btw? – iAteABug_And_iLiked_it Jun 03 '14 at 21:48

1 Answers1

1

DbContext offers you Set method. You may either use it as generic method:

DbSet<Person> people = DbContext.Set<Person>();

or non-generic:

DbSet<Person> people = DbContext.Set(typeof(Person)) as DbSet<Person>;
mr100
  • 4,340
  • 2
  • 26
  • 38
  • But I need to specify DbContext.Set(T) so it just examines Type of T and returns the right entity from datacontext ? :( – iAteABug_And_iLiked_it Jun 03 '14 at 21:47
  • But isn't that what GetTable method does? What is the difference that you're looking for? To find entities by id after calling Set method you may call Find method. – mr100 Jun 04 '14 at 05:32
  • 1
    If you want to find the entity on given table by id just use: context.Set().Find(id) – mr100 Jun 04 '14 at 05:43