简体   繁体   中英

Is it possible to use Entity Framework for unknown database tables?

User selects a database and its table, and will browse the table in a web application. Can I achieve that with Entity Framework? I know EF is ORM framework but in this case, I may not create edmx file for each selection. Even if I did it, how do I create, say, POCO objects dynamically according to the table? What should I do in this case? Do I have to go with low-level ADO.NET?

I think Entity Framework is unnecessary in this case. It might certainly be possible to use EF for something like this, but if it's a simple case of just getting a list of available table names from the database, and letting the user select a table to view, I would simply do the following:

Create drop down list on the site, and populate it using result from query:

SELECT table_name FROM INFORMATION_SCHEMA.TABLES t

Then after the user selects an item from the dropdown, you can bind your grid using Ado.net. Something like:

string tableName = "get value from dropdown";  
DataTable dt = new DataTable();

using (SqlConnection conn = new SqlConnection("connection string here"))
{
    string sql = string.Format("select * from {0}", tableName);
    SqlDataAdapter da = new SqlDataAdapter(sql, conn);
    da.Fill(dt);
}

// bind dt to your grid or gui component here.

Edit Well I know you can do this at least partially. You can definitely let the user select a database/table because you can provide your own connection string/EntityConnect object to the Contexts constructor. I'm not sure how you can go about creating entities dynamically though, I think you would have to have an edmx file that already has all the entities generated or write them yourself from before.

您必须首先将EF指向每个数据库,而不是期望EF动态地查看应用程序中的新数据库。

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