使用泛型可以在不知道类型的情况下从EntityFramework获取对象吗?

我在想一些大致如下的事情:

public T GetObjectByID<T>(int id)
{
   return (from i in myDatabase.T where i.ID == id select i);
}

这可行吗?我可以用反射法取T.GetType().Name,然后用它来做桌子吗?

EDIT
Another hangup, is that not all tables available to me use "ID" as their unique column name.

推荐答案

Finally solved the issue with this:
http://pastebin.com/kjXUKBNS

要调用代码,我使用以下命令:

// Get the id of the object we are saving
PropertyInfo prop = GetProperty<TEntity>(entity, entity.EntityKey.EntityKeyValues[0].Key);
string entityID = prop.GetValue(entity, null).ToString();

// Get the current version of this object
var originalEntity = GetEntity<TEntity>(PropertyEquals, entityID);

这就假设您正在搜索的主键是主键列表中的第一个主键.

Asp.net相关问答推荐

.net 中的 [] 括号是什么?

InvalidOperationException:在程序集上找不到UserSecretsIdAttribute

如何在asp.net中单击按钮的新选项卡中打开页面?

asp.net 单选按钮分组

静态字段与会话变量

SameSite 属性如何自动添加到我的 Asp.net_SessionID cookie 中?

我可以在 Visual Studio 2010 中将任务列表项添加到 csHTML 吗?

这两种方法有什么区别?

MvcBuildViews true 与 ASP.NET MVC 2 中的实体框架

在 IIS 上托管 ASP.NET 5 项目

为什么aspx文件会返回404(找不到页面)

温莎城堡有什么缺点吗?

ASP.NET 中的 <% %>(嵌入式代码块)

解析器错误消息:无法加载类型网络营销

如何在 ASP.Net Gridview 中添加确认删除选项?

Web API 必填参数

哪个控件导致了回发?

ASP.NET 按钮重定向到另一个页面

主机与 DnsSafeHost

ASP.net 判断页面是 http 还是 https