C#中如何使用反射动态映射数据库字段?示例是什么?

来源:这里教程网 时间:2026-02-21 17:27:05 作者:

在C#中使用反射动态映射数据库字段,通常用于将查询结果(如

IDataReader
DataTable
)自动填充到实体对象中。这种方式可以避免为每个实体写重复的赋值代码,提升开发效率。

基本思路

通过反射获取目标类型的属性,然后根据数据库字段名与属性名的匹配关系,动态设置对象属性的值。

示例:使用反射将 IDataReader 映射到实体对象

以下是一个完整的示例,展示如何将
SqlDataReader
的数据映射到一个 C# 类实例中:

1. 定义实体类

假设有一个用户表,对应如下实体: ```csharp public class User { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } } ```

2. 编写通用映射方法

使用反射读取字段并赋值: ```csharp using System; using System.Data; using System.Reflection;

public static class DataMapper { public static T Map(IDataReader reader) where T : new() { T instance = new T(); Type type = typeof(T);

    // 获取所有公共属性
    PropertyInfo[] properties = type.GetProperties();
    for (int i = 0; i < reader.FieldCount; i++)
    {
        string fieldName = reader.GetName(i); // 数据库字段名
        object value = reader.GetValue(i);   // 字段值
        // 查找匹配的属性(忽略大小写)
        PropertyInfo property = Array.Find(properties, 
            p => string.Equals(p.Name, fieldName, StringComparison.OrdinalIgnoreCase));
        if (property != null && value != DBNull.Value)
        {
            // 处理可空类型和类型转换
            Type propType = property.PropertyType;
            if (Nullable.GetUnderlyingType(propType) is Type underlyingType)
            {
                propType = underlyingType;
            }
            object convertedValue = Convert.ChangeType(value, propType);
            property.SetValue(instance, convertedValue);
        }
    }
    return instance;
}

}

<p><strong>3. 使用示例</strong></p>
<font color="#2F4F4F">从数据库读取数据并映射为 User 对象:</font>
```csharp
using (var connection = new SqlConnection("your_connection_string"))
{
    connection.Open();
    using (var cmd = new SqlCommand("SELECT Id, Name, Email FROM Users", connection))
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            User user = DataMapper.Map<User>(reader);
            Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Email: {user.Email}");
        }
    }
}

注意事项与优化建议

实际使用中可考虑以下几点:

性能:反射有一定开销,频繁调用时可缓存属性映射关系(如用 Dictionary 存储字段名到 PropertyInfo 的映射) 字段别名支持:可在属性上使用自定义特性标记数据库字段名,实现更灵活的映射 错误处理:添加 try-catch 避免因类型不匹配导致异常 泛型扩展:可将方法扩展为返回
List<t></t>
,一次性映射多行数据

基本上就这些。这种方式在手写 ORM 或数据访问层时非常实用,能显著减少样板代码。

相关推荐