【问题标题】:GetCustomAttributes and [DatabaseGenerated(DatabaseGeneratedOption.Computed)]GetCustomAttributes 和 [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
【发布时间】:2021-12-01 02:42:38
【问题描述】:
在获取此类属性时如何跳过计算列?我可以为 NotMapped 做,但不确定DatabaseGenerated(DatabaseGeneratedOption.Computed)?
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool AAUProcessing { get; set; }
跳过未映射和计算的列
var props = typeof(TK).GetProperties()
.Where(propertyInfo => !propertyInfo.GetCustomAttributes(typeof(NotMappedAttribute)).Any())
.ToArray();
【问题讨论】:
标签:
c#
.net
entity-framework
reflection
ef-code-first
【解决方案1】:
只需将其转换为正确的类型 (DatabaseGeneratedAttribute),您就可以检查它是否具有您认为合适的任何属性。
以下示例将过滤掉计算和未映射的属性:
void Main()
{
var props = typeof(TK).GetProperties()
.Where(IsNotMapped)
.Where(IsNotComputedColumn)
.ToArray();
foreach (var property in props)
{
Console.WriteLine(property.Name);
}
}
static bool IsNotMapped(PropertyInfo propertyInfo)
{
return !propertyInfo
.GetCustomAttributes(typeof(NotMappedAttribute))
.Any();
}
static bool IsNotComputedColumn(PropertyInfo propertyInfo)
{
return !propertyInfo
.GetCustomAttributes(typeof(DatabaseGeneratedAttribute))
.Cast<DatabaseGeneratedAttribute>()
.Any(a => a.DatabaseGeneratedOption == DatabaseGeneratedOption.Computed);
}
public class TK
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool IsComputed { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public bool IsIdentity { get; set; }
[NotMapped]
public bool NotMapped { get; set; }
public bool StandardColumn { get; set; }
}
输出是
IsIdentity
StandardColumn