遍历通过域模型上的linq查询返回的对象的属性和值 [英] Iterate through properties and values of an object returned via a linq query on a domain model

查看:140
本文介绍了遍历通过域模型上的linq查询返回的对象的属性和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在关系数据库中有一个自定义实体,该实体已通过域模型映射到CLR.因此,通过使用以下语句,我可以通过域模型上的LINQ查询将数据库中的实体拉入内存,就像这样;

I have a custom entity in a relational database that I have mapped to the CLR via a domain model. So by using the following statement, I can pull in an entity from my database into memory via a LINQ query on the domain model, like so;

var inspection = (from i in dbContext.New_testinspectionExtensionBases
              where i.New_testinspectionId == currentInspection   
              select i).First();                         

我需要访问此实体上的属性/字段,我需要能够确定属性/字段名称及其值.我想遍历内存中的这些项目,并将其名称和值写到控制台.

There are properties/fields on this entity that I need access to, I need to be able to determine the property/field name as well as it's value. I want to loop through these items in memory, and write out their names and values to the console.

我尝试使用这种方法,但无法弄清楚如何纠正语法(也不知道GetProperties是使用的正确方法,由于某种原因,GetFields并未返回任何内容,因此我以为是这种方式),但这并不重要,因为我所需要做的就是读取对值的访问权限;

I tried using this approach, but couldn't figure out how to correct the syntax (Nor am I sure that GetProperties is the correct method to use, GetFields wasn't returning anything for some reason so I assumed this was the way to go) but it doesn't really matter since all i need is read access to the value;

var inspectionReportFields = inspection.GetType().GetProperties(); 
// I called this inspectionReportfields because the entity properties correspond to 
// form/report fields I'm generating from this data.

foreach (var reportField in inspectionReportFields)
{
    var value = reportField.GetValue();
    Console.WriteLine(reportField.Name);
    Console.WriteLine(value);
}

在使用诸如EF或openaccess之类的域模型时,是否有更简单的方法来获取属性/字段值?如果没有,我会以正确的方式进行操作吗?最后,如果是这样,如何在值变量声明中修复语法?

Is there an easier way to get the property/field value when utilizing a domain model like EF or openaccess? If not, am I going about it the right way? And lastly, if so, how do I fix the syntax in the value variable declaration?

以下是域模型生成的代码中的一些示例字段/属性,以供参考;

Here are some sample fields/properties from the code generated by the domain model, for reference;

    private int? _new_systemGauges;
    public virtual int? New_systemGauges 
    { 
        get
        {
            return this._new_systemGauges;
        }
        set
        {
            this._new_systemGauges = value;
        }
    }

    private int? _new_systemAlarm ;
    public virtual int? New_systemAlarm 
    { 
        get
        {
            return this._new_systemAlarm;
        }
        set
        {
            this._new_systemAlarm = value;
        }
    }

推荐答案

我假设您正在尝试定义一种通用方法来转储"对象,而不了解其结构.如果是这样,那么您将以正确的方式进行操作.您可以使用反射(GetType()和关联的Type类方法)检查​​对象并返回其信息.

I assume that you're trying to define a general-purpose way to "dump" an object without knowing anything about its structure. If so, then you are going about things the correct way. You use reflection (GetType() and the associated Type class methods) to inspect the object and return its information.

GetFields()没有返回任何内容的原因是您可能未提供正确的绑定标志.特别是,如果您调用不带任何参数的重载,则只会返回public字段;如果您想要私有字段,则需要专门询问.

The reason GetFields() didn't return anything is that you likely did not supply the right binding flags. In particular, if you call the overload that doesn't take any parameters, you only get back public fields; if you want private fields you need to ask for them specifically.

在您的情况下,GetFields(BindingFlags.NonPublic)会给您返回_new_systemGauges_new_systemAlarm字段,而GetProperties()会给您返回New_systemAlarmNew_systemAlarm属性.

In your case, GetFields(BindingFlags.NonPublic) would give you back the _new_systemGauges and _new_systemAlarm fields, while GetProperties() would give you back the New_systemAlarm and New_systemAlarm properties.

您错过的另一个关键因素是您要获取的数据是 type 元数据;它定义了class的结构,而不是任何特定的实例.如果您想知道特定实例的属性值是什么,则需要提出以下要求:

The other key element you missed is that the data you are getting back is the type metadata; it defines the structure of the class, and not any particular instance. If you want to know what the value of a property for a specific instance is, you need to ask for that:

foreach (var prop in obj.GetType().GetProperties())
{
  Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj, null));
}

您可以从类型的元数据中获得PropertyInfo元素之一,可以在该类型的任何实例上请求该属性值.它不必与您最初使用的实例相同.例如:

One you have one of the PropertyInfo elements from the type's metadata, you can ask for that property value on any instance of that type. It doesn't have to be the same instance that you originally used. For example:

var objs = somelist.Where(x => x.Id == 1);
foreach (var prop in objs.First().GetType().GetProperties())
{
  int x = 0;
  foreach (var obj in objs)
  {        
    if (prop.PropertyType.Name.Equals("Int32"))
    {
      int val = (int)prop.GetValue(obj, null);
      Console.WriteLine("Obj #{0}: {1} = 0x{2:x8}", x++, prop.Name, val);
    }
    else if (prop.PropertyType.Name.Equals("Decimal"))
    {
      int val = (decimal)prop.GetValue(obj, null);
      Console.WriteLine("Obj #{0}: {1} = {2:c2}", x++, prop.Name, val);
    }
    else
    {
      Console.WriteLine("Obj #{0}: {1} = '{2}'", x++, prop.Name, prop.GetValue(obj, null));
    }
  }
}

从技术上讲,您应该检查GetIndexParameters的结果以查看属性是否已建立索引; GetValuenull参数实际上是一个索引值数组.

Technically you should check the result of GetIndexParameters to see if a property is indexed or not; the null parameter to GetValue is actually an array of index values.

要转换返回的值,您可以使用类型转换,或者如果您想更灵活一些,请使用Convert类的方法.区别在于,例如,如果您具有short属性,则GetValue()将返回一个装箱的short,您不能随后将其作为int进行类型转换.您必须先将其拆箱到short.使用Convert.ToInt32()将执行所有必需的步骤,以从可转换为整数的任何属性中获取int值.

To convert the value you get back you can either use typecasts, or if you want to be a bit more flexible, use the Convert class's methods. The difference is, for example, if you have a short property, GetValue() will return a boxed short, which you cannot then typecast as an int; you have to unbox it to a short first. Using Convert.ToInt32() will perform all of the needed steps to get an int value out of any property that is convertible to an integer.

在引用类型之间进行转换更容易,因为您可以仅使用isas来实现.这些功能就像您期望的那样,具有反射的"属性值.

Converting between reference types is easier since you can just use is and as for that; those work just like you'd expect with "reflected" property values.

这篇关于遍历通过域模型上的linq查询返回的对象的属性和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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