根据ID的EntityFramework找对象吗? [英] EntityFramework Get object by ID?

查看:122
本文介绍了根据ID的EntityFramework找对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能与泛型摆脱我的EntityFramework对象不知道类型?

Is it possible with Generics to get an object from my EntityFramework without knowing the type?

我沿着线的思维东西

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

是可行的?莫非我使用反射以某种方式采取 T.GetType()。名称并使用该表?

Is that doable? Could I use Reflection to somehow take T.GetType().Name and use that for the table?

修改结果
另一个挂断,就是不能提供给我的所有表使用身份证作为其独特的列名。

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

推荐答案

终于解决了问题,与此:结果
http://pastebin.com/kjXUKBNS

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

要调用code我用这样的:

To call the code I use this:

// 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);

这使得假设您正在搜索的主键是在主键列表中的第一个。

This makes the assumption that the Primary Key you are searching on is the first one in the list of Primary Keys.

这篇关于根据ID的EntityFramework找对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆