Setting sub object property with ILGenerator.Emit

I have some code that uses IlGenerator.Emit to create and populate a generic object using a datareader. It works great, but I need to extend it to populate simple child objects when the database field name contains an underscore character.

For example, a database field named "Address_Line1" should populate the Line1 property, which is the Address property of the Entity. In C # code which is basically ...

Entity.Address.Line1 = "value from reader";

      

I tried writing C # code and used ILSpy to try and identify the IL code I should be writing, but I keep getting memory errors etc.

The code below includes the currently valid IL code and I've included my commented code attempt. Can anyone help me?

public static DynamicBuilder<T> CreateBuilder(IDataRecord reader)
{
    var result = new DynamicBuilder<T>();
    var method = new DynamicMethod("DynamicCreate", typeof(T), new Type[] { typeof(IDataReader) }, typeof(T), true);

    var generator = method.GetILGenerator();

    generator.DeclareLocal(typeof(T));
    generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
    generator.Emit(OpCodes.Stloc_0);

    var getValue = reader.GetType().GetMethod("get_Item", new Type[] { typeof(int) });

    for (int i = 0; i < reader.FieldCount; i++)
    {
        var name = reader.GetName(i).Split('_'); // MY CODE
        var propertyInfo = typeof(T).GetProperty(name[0]);

        if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
        {
            var endIfLabel = generator.DefineLabel();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldc_I4, i);
            generator.Emit(OpCodes.Callvirt, typeof(IDataRecord).GetMethod("IsDBNull"));
            generator.Emit(OpCodes.Brtrue, endIfLabel);

            generator.Emit(OpCodes.Ldloc_0);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldc_I4, i);
            generator.Emit(OpCodes.Callvirt, getValue);

            if (propertyInfo.PropertyType.Name.ToLower().Contains("nullable"))
                generator.Emit(OpCodes.Unbox_Any, GetNullableType(reader.GetFieldType(i)));
            else
                generator.Emit(OpCodes.Unbox_Any, reader.GetFieldType(i));

            // START MY CODE TO GET THE SUB PROPERTY
            if (name.Length > 1)
            {
                generator.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod());
                propertyInfo = propertyInfo.PropertyType.GetProperty(name[1]);
            }
            // END MY CODE

            generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
            generator.MarkLabel(endIfLabel);
        }
    }

    generator.Emit(OpCodes.Ldloc_0);
    generator.Emit(OpCodes.Ret);

    result.handler = (Load)method.CreateDelegate(typeof(Load));
    return result;
}

      

+3


source to share


2 answers


Code like this:

static Entity DynamicCreate(IDataReader reader)
{
    var entity = new Entity();
    entity.Property = (int)reader[0];
    return entity;
}

      

compiled to IL, which looks exactly the same as the code you are using (nonessential parts omitted):

ldloc.0     // entity
ldarg.0     // reader
ldc.i4.0    
callvirt    System.Data.IDataRecord.get_Item
unbox.any   System.Int32
callvirt    UserQuery+Entity.set_Property

      

But if you add this second resource access:

static Entity DynamicCreate(IDataReader reader)
{
    var entity = new Entity();
    entity.SubEntity.Property = (int)reader[0];
    return entity;
}

      



Then the IL looks like this:

ldloc.0     // entity
callvirt    UserQuery+Entity.get_SubEntity
ldarg.0     // reader
ldc.i4.0    
callvirt    System.Data.IDataRecord.get_Item
unbox.any   System.Int32
callvirt    UserQuery+SubEntity.set_Property

      

Note that the call get_SubEntity

is between ldloc.0

and ldarg.0

and not right before set_Property

as in your code, so you need to move it in your code as well.

The reason your code doesn't work is because IL is a stack based language: when you call a method with no parameters (like the getter property), the object at the top of the stack (which is the result here unbox.any

) will be used like this

, what you don't like here. Basically, your code is trying to do something like:

entity.Property = ((int)reader[0]).SubEntity;

      

+3


source


I suggest not using IL / Emit code at all, as it is difficult to create expressions with it. Try using the new Roslyn to generate delegates instead.



Here are some examples: https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples

-1


source







All Articles