linq to sql仅从对象中非空的列中选择数据

时间:2010-09-01 15:57:01

标签: linq-to-sql reflection properties

我正在尝试构建一个包含linq到sql对象中字段值的字符串。 问题是,我只想抓住非空的字段

我相信有办法做到这一点。 谁能开导我?

mylinqdatacontext dc = new mylinqdatacontext;
StringBuilder sb = new StringBuilder();
mylinqtype item = (from x in dc.mylinqtypes where x.id.equals(1)).single();
var props = typeof(mylinqtype).GetProperties();

foreach(PropertyInfo p in props){

  if(item... != null){
    sb.append(p.name + " :" + item[p].value; //or some such i dont really know
  }
}

任何非常感谢的帮助

我试过了

object theValue =  p.getgetmethod().invoke(item, null); 

但它抛出了System.Reflection.TargetException 感谢

NAT

2 个答案:

答案 0 :(得分:1)

这是未经测试的,但我认为它应该至少让你接近:

SomeDataContext dc = new SomeDataContext();
StringBuilder sb = new StringBuilder();

SomeItem item = (from x in dc.SomeItems where x.SomeItemId == 1 select x).Single();
PropertyInfo[] props = item.GetType().GetProperties();

foreach (PropertyInfo p in props)
{
    if (p.CanRead) // might need more tests here for various attributes of the property
    {
        object val = p.GetValue(item, null);

        if (val != null)
        {
            sb.Append(p.Name + " : " + val);
        }
    }
}

答案 1 :(得分:0)

using (var dc = new DataContext())
{
    var result = dc.Entities.Where(x => c.Column != null).Select(x => x.Column)
                 .Aggregate((x, y) => x + y);
}