Search code examples
asp.net-mvcasp.net-mvc-4entity-framework-5

c# mvc 4 EF 5 get dbset from dbcontext without knowing the tabel name


I have a Users entity set and a Administrators entity set. I want to get a list of items that can be a IEnumerable<Users> or a IEnumerable<Administrators> from the DBContext

i want to be able to do

Type dbContextType = db.GetType();

Type tableType = dbContextType.GetProperty("users", 
    BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance
).PropertyType;

var items = db.Database.SqlQuery(tableType , "SELECT * FROM users");

the problem is that tableType is a typeof DbSet and i need a typeof Users


Solution

  • Simplier than i thought

    Type typeDB = Type.GetType("Models.User");
    
    var items = db.Database.SqlQuery(typeDB, "SELECT * FROM users WHERE IdUser = '"+id+"'");
    

    items is now a System.Data.Entity.Internal.InternalSqlQuery witch has a Enumerator with our objects. Problem is that we can't send this object to a strongly typed view.

    Therefor we have to cast it.If we don't know the class we want it to be cast to , then we can cast it to object type. And the view we are going to send it to will do the specific cast to the strongly typed object.

    return View("Users", items.Cast< object >().ElementAt(0));
    

    Now we have one controller that we can use for multiple strongly typed views.