首先通过反射获取实体类型属性,再与数据库字段名匹配并自动赋值。示例中定义User类,编写通用Map方法,利用PropertyInfo遍历IDataReader字段,忽略大小写匹配属性名,处理可空类型转换后设值,最终实现SqlDataReader到对象的映射,提升数据访问层开发效率。

在C#中使用反射动态映射数据库字段,通常用于将查询结果(如 IDataReader 或 DataTable)自动填充到实体对象中。这种方式可以避免为每个实体写重复的赋值代码,提升开发效率。
通过反射获取目标类型的属性,然后根据数据库字段名与属性名的匹配关系,动态设置对象属性的值。
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
// 获取所有公共属性
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}");
}
}
}实际使用中可考虑以下几点:
List<T>,一次性映射多行数据基本上就这些。这种方式在手写 ORM 或数据访问层时非常实用,能显著减少样板代码。
以上就是C#中如何使用反射动态映射数据库字段?示例是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号