Dapper里使用Attribute自定义映射关系

目的将book表中的id,name,price 映射到Book类中的Id1,Name1,Price1

    class Program
    {        
        static SQLiteConnection conn;
        static string dbStr = "test.db";
        static void Main(string[] args)
        {
            SqlMapper.SetTypeMap(typeof(Book), new CustomTypeMap<Book>());//定义映射规则
            SQLiteConnection.CreateFile(dbStr);
            conn = new SQLiteConnection($"Data Source={dbStr};Version=3;");
            string sql = "create table book (id int,name varchar(20), price double)";         

            conn.Execute(sql);
            sql = "insert into book values(@id1,@name1,@price1)";
            conn.Execute(sql, new Book());

            sql = "select * from book";
            var books = conn.Query<Book>(sql);

            Console.ReadLine();
        }
    }

    public class Book
    {
        [Column("name")]
        public string Name1 { get; set; }
        [Column("id")]
        public int Id1 { get; set; }
        [Column("price")]
        public double Price1 { get; set; }
    }

    public class CustomTypeMap<T> : SqlMapper.ITypeMap
    {
        public ConstructorInfo FindConstructor(string[] names, Type[] types)
        {
            return null;
        }

        public ConstructorInfo FindExplicitConstructor()
        {
            return typeof(Book).GetConstructor(new Type[0]);
        }

        public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
        {
            return null;
        }

        public SqlMapper.IMemberMap GetMember(string columnName)
        {
            return new CustomMemberMap(columnName, _dict[columnName]);
        }

        private Dictionary<string, PropertyInfo> _dict = new Dictionary<string, PropertyInfo>();
        public CustomTypeMap()
        {
            Type type = typeof(T);
            var ps = type.GetProperties();
            foreach (var p in ps)
            {
                var at = p.GetCustomAttribute<ColumnAttribute>();
                if (at != null)
                {
                    if (!string.IsNullOrWhiteSpace(at.ColumnName))
                        _dict.Add(at.ColumnName, p);
                }
            }
        }
    }
    [AttributeUsage(AttributeTargets.Property)]
    public class ColumnAttribute : Attribute
    {
        public string ColumnName { get; }
        public ColumnAttribute(string columnName)
        {
            ColumnName = columnName;
        }
    }

    public class CustomMemberMap : SqlMapper.IMemberMap
    {
        public CustomMemberMap(string column,PropertyInfo propertyInfo)
        {
            ColumnName = column;
            Property = propertyInfo;
        }
        public string ColumnName { get; }

        public Type MemberType => Field?.FieldType ?? Property?.PropertyType ?? Parameter?.ParameterType;

        public PropertyInfo Property { get; }

        public FieldInfo Field { get; }

        public ParameterInfo Parameter { get; }
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dapper是一种轻量级ORM(对象关系映射)工具,它可以将数据库中的数据映射到.NET类型中。Dapper支持自定义属性映射,这使得我们可以将数据库中的列映射到.NET类型中的自定义属性上。 Dapper使用`Map`方法来进行自定义属性映射。例如,如果我们有一个名为`Person`的类,它有一个名为`LastName`的自定义属性,我们可以使用以下代码将数据库中的`last_name`列映射到该自定义属性上: ```csharp public class Person { public string FirstName { get; set; } [CustomMapping("last_name")] public string LastName { get; set; } } var sql = "SELECT first_name, last_name FROM people WHERE id = @id"; var person = connection.QuerySingleOrDefault<Person>(sql, new { id = 1 }); ``` 在上面的代码中,我们使用了`CustomMapping`属性来标记`LastName`属性,指定它应该映射到数据库中的`last_name`列。然后,我们可以使用Dapper的`QuerySingleOrDefault`方法来执行查询并将结果映射到`Person`对象中。 注意,`CustomMapping`属性需要自己实现。下面是一个简单的实现示例: ```csharp [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class CustomMappingAttribute : Attribute { public string ColumnName { get; private set; } public CustomMappingAttribute(string columnName) { ColumnName = columnName; } } ``` 在上面的代码中,`CustomMappingAttribute`是一个自定义属性,它具有一个名为`ColumnName`的属性,用于保存数据库列的名称。它还具有一个构造函数,用于设置`ColumnName`属性的值。这样,我们就可以在`Person`类中使用`CustomMapping`属性来指定属性应该映射到哪个列。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值