如何从T4中的EntityModel访问其他实体属性的“常规”属性?

时间:2011-07-08 06:22:54

标签: entity-framework entity-framework-4 code-generation t4

我使用以下代码来获取实体的所有属性

IList<EdmProperty> list = entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity)

然后我遍历这些列表,访问每个Property并阅读Property Properties(是的,很多属性,希望没有人会感到困惑)。

虽然我可以轻松访问General属性,但我不知道如何访问实体属性的其他属性,例如Max Length&amp; Fixed Length

3 个答案:

答案 0 :(得分:1)

这些属性不属于PrimitiveType。它们直接位于p.TypeUsage Facets属下的{{1}}。

答案 1 :(得分:1)

请尝试以下代码:

var MaxLength = (property as EdmMember).TypeUsage.Facets.Where(f => f.Name == "MaxLength").SingleOrDefault();
int maxLength = -1;
if(MaxLength != null)
  maxLength = (int)MaxLength.Value;  

您可以在模板代码中使用maxLength变量。可以以类似的方式访问任何其他方面。

答案 2 :(得分:1)

  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;
        }
    }