简体   繁体   中英

How to find the table i want in an sql server using entity framework

I am using a method which its purpose it to read from tables. The method has an input parameter, a string which will hold the name of the table I will pass and I want to read from. There are multiple tables. My code so far:

public List<dataTable> GetData(string name)
    {
        TableEntities db = new TableEntities();
        db.Database.Connection.Open();
        foreach (var readDb in db.SOMETHING_HERE) //here it should find the table which is equal to the table I'm passing as string name
        {
            dataTable data = new dataTable();
            data.name = readDb.name;

There are many option at db. but I don't know which fits my needs.

I think you need to use reflection to achieve that: MSDN Reflection reference

You may want to try something along these lines: (assuming sample tables Employees and Departments)

public List<dataTable> GetData(string name)
{
    using(TableEntities db = new TableEntities())
    {
        if(new Employees().GetType().ToString().Equals(name))
            //Do query
    }
}

It's not pretty, but you can try this:

        using (TableEntities db = new TableEntities())
        {
            var type = Type.GetType("namespace." + tableName);

            var query = db.Database.SqlQuery(type, "SELECT * FROM " + tableName);

            foreach (var row in query)
            {
                PropertyInfo prop = type.GetProperty("NAME");
                string name = (string)prop.GetValue(row);
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM