首页 新闻 会员 周边

在Linq to entity中使用反射

0
悬赏园豆:10 [待解决问题]

我想动态的传给Linq一个对象的属性名,然后根据属性名进行排序操作,下面代码是在Linq中通过反射根据一个属性(FirstName)查找Person对象,但在运行时会报错.

请教linq lamda表达式中能这样使用吗?

schoolContext = new SchoolEntities();            

IQueryable<Person> person = schoolContext.Person.Where<Person>(p => p.GetType().GetProperty("FirstName").GetValue(p, null).ToString() == "Kim");

foreach(Person p in person)            

{                

MessageBox.Show(p.LastName);            

}

bluefirework的主页 bluefirework | 初学一级 | 园豆:18
提问于:2013-04-27 17:32
< >
分享
所有回答(2)
0
Dictionary<String, Func<User, IComparable>> list;

userList = User.GetUserList();
list = new Dictionary<String, Func<User, IComparable>>();
list.Add("UserName", currentUser => currentUser.UserName);
list.Add("UserID", currentUser => currentUser.UserID);



//用反射动态添加自定义属性。
public static PropertyInfo[] GetInfo<K>(K item) where K : class
{
  PropertyInfo[] propertyList;
  Type typeInfo;

  typeInfo = item.GetType();
  propertyList = typeInfo.GetProperties();

  return propertyList;
}

public static IComparable OrderByProperty<T>(String propertyName, T item)
  where T : class
{
  PropertyInfo[] propertyList;

  propertyList = GetInfo(item);

  return (IComparable)propertyList.First(currentProperty
    => currentProperty.Name == propertyName).GetValue(item, null);
}

//排序例子。
var test = userList.OrderBy(currentUser
  => DynamicPropertySort.OrderByProperty("UserID", currentUser)).ToList();
悟行 | 园豆:12559 (专家六级) | 2013-04-27 19:20

userList = User.GetUserList();
这句是什么意思没搞懂?

支持(0) 反对(0) bluefirework | 园豆:18 (初学一级) | 2013-04-28 09:39

@bluefirework: 一个泛型集合,你可以换成你的。

支持(1) 反对(0) 悟行 | 园豆:12559 (专家六级) | 2013-04-28 12:32

@荒野的呼唤: 

上边定义的Dictionary<String, Func<User, IComparable>> list程序里边咋个没用到呢?
支持(0) 反对(0) bluefirework | 园豆:18 (初学一级) | 2013-05-05 12:47
0

反射,这个还真没用到,也相学习了。!

jerry-Tom | 园豆:4077 (老鸟四级) | 2013-04-28 10:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册