Dapper扩展程序自定义ClassMapper不会在Insert()上调用

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

我正在使用Dapper Extensions,并定义了自己的自定义映射器来处理带有复合键的实体。

     public class MyClassMapper<T> : ClassMapper<T> where T : class
{
    public MyClassMapper()
    {
        // Manage unmappable attributes

        IList<PropertyInfo> toIgnore = typeof(T).GetProperties().Where(x => !x.CanWrite).ToList();

        foreach (PropertyInfo propertyInfo in toIgnore.ToList())
        {
            Map(propertyInfo).Ignore();
        }

        // Manage keys

        IList<PropertyInfo> propsWithId = typeof(T).GetProperties().Where(x => x.Name.EndsWith("Id") || x.Name.EndsWith("ID")).ToList();
        PropertyInfo primaryKey = propsWithId.FirstOrDefault(x => string.Equals(x.Name, $"{nameof(T)}Id", StringComparison.CurrentCultureIgnoreCase));

        if (primaryKey != null && primaryKey.PropertyType == typeof(int))
        {
            Map(primaryKey).Key(KeyType.Identity);
        }
        else if (propsWithId.Any())
        {
            foreach (PropertyInfo prop in propsWithId)
            {
                Map(prop).Key(KeyType.Assigned);
            }
        }

        AutoMap();
    }
}

我也有这个测试用例来测试我的映射器:

    [Test]
    public void TestMyAutoMapper()
    {
        DapperExtensions.DapperExtensions.DefaultMapper = typeof(MyClassMapper<>);

        MySubscribtionEntityWithCompositeKey entity = new MySubscribtionEntityWithCompositeKey
        {
            SubscriptionID = 145,
            CustomerPackageID = 32
        };

        using (var connection = new SqlConnection(CONNECTION_STRING))
        {
            connection.Open();
            var result = connection.Insert(entity);
            var key1 = result.SubscriptionID;
            var key2 = result.CustomerPackageID;
        }
    }

注意,我在测试用例中设置了默认的映射器。

插入失败,我注意到从未调用过我的客户映射器。我在该主题的github页面上没有文档,所以我不确定是否还需要做其他事情来使dapper扩展使用我的mapper。

提前感谢!

automapper sql-insert dapper composite-primary-key dapper-extensions
1个回答
1
投票

看着您的问题,您正在尝试

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