Dapper如何设置属性而不使用setter

问题描述 投票:0回答:1

我有一个模特:

    public class Model
    {
        public int Id { get;}

        public string Name { get; }

        public string AnotherName { get; }
    }

默认构造函数,没有设置方法,因此IL生成的类中没有公共设置方法。

但是Dapper以某种方式初始化我的数据。所有属性均已填写。

                var sql = $@"SELECT id as Id, name as Name, another_name as AnotherName FROM dapper";

                var raws = (connection.QueryAsync<Model>(sql).Result).AsList();

我已经找到源代码,并且它们通过Setter方法进行设置,但是当我尝试像Dapper那样获取setter时,我得到了null methodInfo。这是一些Dapper源代码SqlMapper:3320

                    if (specializedConstructor == null)
                    {
                        // Store the value in the property/field
                        if (item.Property != null)
                        {
                            il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, DefaultTypeMap.GetPropertySetter(item.Property, type));
                        }
                        else
                        {
                            il.Emit(OpCodes.Stfld, item.Field); // stack is now [target]
                        }
                    }

DefaultTypeMap.GetPropertySetter

        internal static MethodInfo GetPropertySetter(PropertyInfo propertyInfo, Type type)
        {
            if (propertyInfo.DeclaringType == type) return propertyInfo.GetSetMethod(true);

            return propertyInfo.DeclaringType.GetProperty(
                   propertyInfo.Name,
                   BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                   Type.DefaultBinder,
                   propertyInfo.PropertyType,
                   propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(),
                   null).GetSetMethod(true);
        }

您可以编写示例,我也可以这样做,您将看到您的属性是否没有任何设置方法,那么设置方法的信息将为null。

.net reflection orm dapper getter-setter
1个回答
0
投票

enter image description here

它将属性存储在内部Dapper模型中,如果该属性不具有属性-它将通过后备字段对其进行设置。

© www.soinside.com 2019 - 2024. All rights reserved.