Iterate through an object's attributes and values returned by a linq query on a domain model.

c# entity-framework linq telerik-open-access

Question

I've used a domain model to translate a custom entity from a relational database to the CLR. I can thus get an object from my database into memory using the following line, which uses a LINQ query on the domain model, as follows;

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

I require access to certain fields and properties on this entity, and I need to know both the name and value of each field and property. I want to send out the names and values of these things in memory to the terminal using a loop.

Although I'm not certain GetProperties is the right method to use (GetFields wasn't returning anything for some reason, so I assumed this was the way to go), I tried using this method and was unable to figure out how to correct the syntax, 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);
}

When using a domain model like EF or openaccess, is there a simpler method to get the property/field value? If not, am I approaching the situation correctly? In such case, how can I correct the syntax in the declaration of the value variable?

Here are a few examples of fields and attributes from the domain model's code for your 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;
        }
    }
1
40
8/22/2017 8:35:35 AM

Accepted Answer

I'm assuming you're attempting to provide a general-purpose method of "dumping" an object without any knowledge of its structure. If so, you are approaching the situation correctly. When you reflect (GetType() along with the relatedType class methods) to examine the object and provide back its data.

The causeGetFields() if nothing was returned, you most likely did not provide the correct binding flags. In particular, you only get the results if you call the overload that doesn't accept any arguments.public fields; if you want private fields, you must expressly request them.

As for you,GetFields(BindingFlags.NonPublic) would return to you the_new_systemGauges and _new_systemAlarm while GetProperties() would return the fieldsNew_systemAlarm and New_systemAlarm properties.

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

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

You possess one of thePropertyInfo You may inquire about the value of a property on any instance of a type by providing items from the type's metadata. It's not necessary to utilize the same instance that you used at first. For instance:

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

Technically, you need to examine the outcome ofGetIndexParameters to determine if a property is indexable or not;null variable toGetValue really a collection of index values.

You may use typecasts or, if you want to be a little more flexible, the methods of the Convert class to convert the value you get back. The distinction is that, for instance, if you have ashort property, GetValue() will produce a boxed short that you cannot typecast as an answer.int You must unbox it to use it.short first. UsingConvert.ToInt32() will take all necessary actions to get anint value out of any integer property with the value adaptable to.

Since you can just use, converting between reference types is simpler.is and as for that; they operate in the manner you would anticipate given "reflected" property values.

77
3/15/2012 11:12:34 PM

Popular Answer

GetProperties Yes, it is the right approach.

Change your code to the following to get rid of the compiler error:

var value = reportField.GetValue(inspection, null);

The instance from which you wish to get the value must be sent as aPropertyInfo No particular instance of a class is tied to an object.


Please think about adhering to the accepted.NET name conventions.

The following would result from this:

NewSystemAlarm in place ofNew_systemAlarm
newSystemAlarm or _newSystemAlarm in place of_new_systemAlarm
NewTestInspectionExtensionBases in place ofNew_testinspectionExtensionBases
NewTestInspectionId in place ofNew_testinspectionId



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow