31

In LINQ to SQL, I can create a repository dynamically using DataContext.GetTable<T>. Is there a similar way to do this in Entity Framework 4 other than declaring the properties on the specific DbContext? For example:

public MyDbContext: DbContext
{
    public DbSet<MySet> MySets {get; set;}
}

I would like to know how can I create/get a reference to MySets dynamically as I can with LINQ to SQL as in:

var mySet = MyDbContext.GetTable<MySet>();

3 Answers 3

48

DbContext has method for this:

  var set = context.Set<MyEntity>();
Sign up to request clarification or add additional context in comments.

2 Comments

I have used something similar in my project but i encountered a small problem. The DbSet iscreated dynamically and the in-memory graph works nicely; However, when the time comes to store the data into the database e.g. context.SaveChanges() the following exception is throws: Invalid object name 'dbo.CustomModel'.
Looks like some problem with your mapping because it tries to access db object which doesn't exist
21

Use:

DbSet<MyEntity> set = context.Set<MyEntity>();

Or, if you can't use the generic method:

DbSet set = context.Set(
    typeof( MyEntity )
);

Don't worry about second-loading and duplicating a POCO. Sets are cached internally by the Context.

Comments

2

This is my aproach:

    public static List<T> GetCollection<T>()
    {
        List<T> lstDynamic = null;

        using (MyDbContext db = new MyDbContext())
        {
            DbSet mySet = db.Set(typeof(T));
            mySet.Load();
            var list = mySet.Local.Cast<T>();

            lstDynamic = list.ToList();
        }
        return lstDynamic;
     }

And you call this function as:

List<Customer> lst = StaticClass.GetCollection<Customer>();

This returns your entire collection. I used this to perform a cache functionality for basic tables which don't change its content very often.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.