| 12345678910111213141516171819202122232425262728293031 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Service
- {
- public static class DbExtensions
- {
- // 安全读取 string
- public static string SafeGetString(this IDataRecord reader, string fieldName)
- => reader[fieldName] as string; // DBNull.Value as string → null
- // 安全读取可空值类型(如 int?)
- public static T? SafeGetValue<T>(this IDataRecord reader, string fieldName)
- where T : struct
- {
- var val = reader[fieldName];
- return (val == DBNull.Value) ? null : (T?)val;
- }
- public static void AddParameter(this IDbCommand cmd, string name, object value)
- {
- var param = cmd.CreateParameter();
- param.ParameterName = name;
- param.Value = value ?? DBNull.Value; // 自动转换
- cmd.Parameters.Add(param);
- }
- }
- }
|