我想写一个方法来获取T4模板文件中属性的Nullable状态。
我已经在我的TT文件中写了它,但在T4文件中它是不同的
bool IsRequired(object property) {
bool result=false;
? ? ? ? ? ? ? ? ? ? ? ?
return result;
}
List<ModelProperty> GetEligibleProperties(EnvDTE.CodeType typeInfo, bool includeUnbindableProperties) {
List<ModelProperty> results = new List<ModelProperty>();
if (typeInfo != null) {
foreach (var prop in typeInfo.VisibleMembers().OfType<EnvDTE.CodeProperty>()) {
if (prop.IsReadable() && !prop.HasIndexParameters() && (includeUnbindableProperties || IsBindableType(prop.Type))) {
results.Add(new ModelProperty {
Name = prop.Name,
ValueExpression = "Model." + prop.Name,
Type = prop.Type,
IsPrimaryKey = Model.PrimaryKeyName == prop.Name,
IsForeignKey = ParentRelations.Any(x => x.RelationProperty == prop),
IsReadOnly = !prop.IsWriteable(),
// I Added this >>
IsRequired = IsRequired(prop)
});
}
}
}
怎么做???
答案 0 :(得分:2)
一年后我用同样的问题挣扎,我发现了你的问题。我认为这不可能以简单的方式进行,因为您必须将CodeTypeRef传输到Systemtype。这是一个很好的黑客,适用于模型和mvcscaffolding:
bool IsNullable(EnvDTE.CodeTypeRef propType) {
return propType.AsFullName.Contains(".Nullable<");
}
您应该以这种方式调用此函数:
// I Added this >>
// IsRequired = IsRequired(prop)
IsRequired = IsNullable(prop.Type);
});
答案 1 :(得分:0)
从T4模板中调用它没什么特别的,有吗?见question
我个人喜欢迈克琼斯的答案,为方便起见,转载于此处。
public static bool IsObjectNullable<T>(T obj)
{
// If the parameter-Type is a reference type, or if the parameter is null, then the object is always nullable
if (!typeof(T).IsValueType || obj == null)
return true;
// Since the object passed is a ValueType, and it is not null, it cannot be a nullable object
return false;
}
public static bool IsObjectNullable<T>(T? obj) where T : struct
{
// Always return true, since the object-type passed is guaranteed by the compiler to always be nullable
return true;
}