How to Retrieve Object from Generic Repository or DB Table with String for table name and int for index of record
Sitting on top of a repository pattern, I have classes for each of my objects (i.e. db tables) to allow for type-based data access:
public abstract class ObjectDataAccessBase<T> : IObjectDataAccess<T>
{
public virtual IQueryable<T> FindAll()
{
...
}
public virtual T Get(int? id)
{
...
}
public virtual void Add(T obj)
{
...
}
public virtual void Delete(T obj)
{
...
}
}
That snippet covers the interface, a common pattern I've seen around. So from another place in the app, what I have is a string for the name of the object (i.e. db table, or "T"), and an int representing the index of the object I want in the table, which I want to pass to "Get(int? id)" to return the object in question. But I need to instantiate the correct class first, casted so as to expose the method I need. I'll need to cast the object, too.
The question is: can that be achieved in this scenario? If so, how?
(More detail on th开发者_运维百科e context of the call: I have a table which relates one kind of object to possibly many other objects, so I have in this table a column with 'string name' for DB table, and an 'int id' for the index of the object in the table, and I want to be able to retrieve the object from the table, properly casted, with these two bits of information. Just testing the waters with this pattern, and already I'm wondering whether it's worthwhile...)
Thanks for your help.
Tim.
Use Reflection to create an instance of your repository:
var type = Type.GetType("ObjectDataAccessBase");
type = type.MakeGenericType(Type.GetType("Your T as string"));
var repository = Activator.CreateInstance(type);
var method = type.GetMethod("Get");
var result = method.Invoke(repository, new object[]{ id });
I'm writing without VS, so there may be a mistake or two. But hopefully the above should get you started.
If you will be using strings a lot I suggest you create a static Dictionary<string, IObjectDataAccess>
and instantiate all repositories explicitly.
精彩评论