【问题标题】:How can I access other then the "General" attributes of a Entity-Property from a EntityModel within a T4?如何从 T4 中的 EntityModel 访问实体属性的“常规”属性以外的其他属性?
【发布时间】:2011-10-01 00:41:37
【问题描述】:
我正在使用以下代码来获取实体的所有属性
IList<EdmProperty> list = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity)
然后我遍历这些列表,访问每个属性并读取属性属性(是的,很多属性,希望没有人混淆)。
虽然我可以轻松访问 General 属性,但我不知道如何访问实体属性的其他属性,例如 Max Length 和 Fixed Length
【问题讨论】:
标签:
entity-framework
entity-framework-4
code-generation
t4
【解决方案1】:
这些属性不属于PrimitiveType。它们直接位于p.TypeUsage 属性下的Facets 中。
【解决方案2】:
试试下面的代码:
var MaxLength = (property as EdmMember).TypeUsage.Facets.Where(f => f.Name == "MaxLength").SingleOrDefault();
int maxLength = -1;
if(MaxLength != null)
maxLength = (int)MaxLength.Value;
您可以在模板代码中使用 maxLength 变量。任何其他方面都可以通过类似方式访问。
【解决方案3】:
protected void RecognizeByMetadata(IList<Facet> facets)
{
//Dictionary<string, string> attributes = new Dictionary<string, string>();
//facets.AsParallel().ForAll(x => attributes.Add(x.Name, x.Value + ""));
try{
var t = facets.Where(x => x.Name == "MaxLength").Select(x => x.Value).FirstOrDefault();
if (t != null)
{
string typ = t.GetType().FullName;
this.isMax = (t.ToString() == "Max");
if (!isMax)
this.MaxLength = (int?)t;
}
else
{
isMax = false;
MaxLength = null;
}
this.IsNullable = (bool?)facets.Where(x => x.Name == "Nullable").Select(x => x.Value).FirstOrDefault();
this.Defaultvalue = facets.Where(x => x.Name == "DefaultValue").Select(x => x.Value).FirstOrDefault();
this.IsUnicode = (bool?)facets.Where(x => x.Name == "Unicode").Select(x => x.Value).FirstOrDefault();
this.IsFixedlength = (bool?)facets.Where(x => x.Name == "FixedLength").Select(x => x.Value).FirstOrDefault();
//string precision = facets.Where(x => x.Name == "Precision").Select(x => x.Value + "").FirstOrDefault();
//string scale = facets.Where(x => x.Name == "Scale").Select(x => x.Value + "").FirstOrDefault();
isRecognized = true;
recognizeUnique();
} catch (Exception e)
{
string mewssage = e.Message;
throw;
}
}