You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#自定义ORM中检测模型属性是否为Key标记主键的方法

解决方案

要实现自动识别带[Key]特性的主键,只需把原来判断属性名是否为Id的逻辑,替换为检测属性是否标记了KeyAttribute即可。

步骤1:引入必要命名空间

确保代码文件顶部添加以下命名空间引用(KeyAttribute位于此命名空间下):

using System.ComponentModel.DataAnnotations;

步骤2:修改判断条件

将原代码中的if (prop[i].Name != "Id")替换为以下逻辑:

// 排除带有[Key]特性的属性
if (prop[i].GetCustomAttribute<KeyAttribute>() == null)

修改后的完整关键代码片段

public T InsertData<T>(T model)
{
    using (SqlConnection SqlConn = new SqlConnection(_connectionString))
    {
        // ...
        PropertyInfo[] prop = typeof(T).GetProperties(); // 建议直接用typeof(T)替代ObjType,逻辑更清晰
        string SqlParameter = "";
        string SqlValue = "";
        for(int i = 0; i < prop.Length; i++)
        {
            // 替换后的判断逻辑:跳过带[Key]特性的主键字段
            if (prop[i].GetCustomAttribute<KeyAttribute>() == null)
            {
                var propValue = prop[i].GetValue(model);
                // 处理空值,同时转义单引号避免SQL语法错误
                var formattedValue = propValue == null 
                    ? "NULL" 
                    : $"'{propValue.ToString().Replace("'", "''")}'";
                
                SqlParameter = string.IsNullOrEmpty(SqlParameter) 
                    ? $"[{prop[i].Name}]" 
                    : $"{SqlParameter},[{prop[i].Name}]";
                SqlValue = string.IsNullOrEmpty(SqlValue) 
                    ? formattedValue 
                    : $"{SqlValue},{formattedValue}";
            }
        }
        // ... 后续执行SQL的逻辑
    }
}

补充说明

  • 若使用的是.NET Framework 4.5以下版本,GetCustomAttribute<T>方法不可用,可改用旧写法:
    if (!prop[i].GetCustomAttributes(typeof(KeyAttribute), false).Any())
    
  • 注意:当前代码直接拼接SQL值存在SQL注入风险,建议后续优化为使用SqlParameter集合构建参数化查询,从根源避免安全问题。

内容的提问来源于stack exchange,提问作者Arc.NET

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:10:32