简体   繁体   English

是否可以对未知数据库表使用实体框架?

[英]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. 用户选择一个数据库及其表,然后将在Web应用程序中浏览该表。 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. 我知道EF是ORM框架,但是在这种情况下,我可能不会为每个选择创建edmx文件。 Even if I did it, how do I create, say, POCO objects dynamically according to the table? 即使我做到了,如何根据表动态创建POCO对象? What should I do in this case? 在这种情况下我该怎么办? Do I have to go with low-level ADO.NET? 我必须使用低级的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: 也许可以将EF用于类似这样的事情,但是如果只是从数据库中获取可用表名列表并让用户选择要查看的表的简单情况,我将简单地执行以下操作:

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. 然后,在用户从下拉列表中选择一项之后,您可以使用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. 您绝对可以让用户选择数据库/表,因为您可以向Contexts构造函数提供自己的连接字符串/ EntityConnect对象。 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. 我不确定如何动态创建实体,我想您将不得不拥有一个已经生成了所有实体的edmx文件,或者自己从以前编写它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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