Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was previously using a DataContext which had a GetTable(type) method to get tables generically. Example:

context.GetTable(myObject.GetType());

Recently my team decided to switch to using ObjectContext with the Entity Framework. Is there a way to get tables by the entity name similar to DataContexts GetTable method without having to specify a specific type? It has to be generic.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
916 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is indeed a very simple way to do this, like so:

public IQueryable GetTable<T>(T entity) where T : class
{
    return context.CreateObjectSet<T>();
}

Now if I create a Person object and pass to it the generic method, the variable below 'allPeople' will be an IQueryable of people from my database which you can iterate though.

Person person = new Person();
IQueryable allPeople = GetTable(person);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...