如何调用GetCustomAttributes时跳过DatabaseGenerated的Computed计算列属性
解决方法
你只需要在原有Where过滤条件中新增DatabaseGeneratedAttribute的判断逻辑即可,最终实现代码会同时过滤标注NotMappedAttribute的属性、以及标注为DatabaseGeneratedOption.Computed的计算列。
修改后的代码如下:
var props = typeof(TK).GetProperties() .Where(propertyInfo => // 过滤标注NotMapped的属性 !propertyInfo.GetCustomAttributes(typeof(NotMappedAttribute)).Any() // 新增过滤:标注DatabaseGenerated且值为Computed的计算列 && !propertyInfo.GetCustomAttributes(typeof(DatabaseGeneratedAttribute)) .Cast<DatabaseGeneratedAttribute>() .Any(attr => attr.DatabaseGeneratedOption == DatabaseGeneratedOption.Computed) ) .ToArray();
如果你的项目运行环境是.NET Core 2.0+ / .NET 5+,可以用更简洁的泛型特性获取方法简化代码:
var props = typeof(TK).GetProperties() .Where(propertyInfo => // 过滤NotMapped属性的极简写法 !propertyInfo.IsDefined(typeof(NotMappedAttribute)) // 空值传播运算符会自动处理无DatabaseGeneratedAttribute的情况 && propertyInfo.GetCustomAttribute<DatabaseGeneratedAttribute>()? .DatabaseGeneratedOption != DatabaseGeneratedOption.Computed ) .ToArray();
注意:代码需要提前引入命名空间
using System.ComponentModel.DataAnnotations.Schema;,否则会找不到对应的特性类。
内容的提问来源于stack exchange,提问作者Mike Flynn
相关产品推荐
相关产品推荐

