Tuesday, October 19, 2010

Get the field size in the entity

In the entity framework, the diagram shown in the Visual Studio contains field information of all tables. You may get the field size that stores in the diagram by using the following method:

public static int GetMaxLength(ObjectContext p,
            string tb_name,
            string fld_name)
        {
            if (p == null)
            {
                throw new ArgumentNullException();
            }

            MetadataWorkspace w = p.MetadataWorkspace;
            var items = w.GetItems(DataSpace.CSpace);

           //i.Properties["tb_name"].TypeUsage.Facets["MaxLength"].Value
            var v = items.Where(i => string.Compare(i.Name, tb_name, true) == 0);
            EntityType et = v.First();

            object obj = et.Properties[fld_name].TypeUsage.Facets["MaxLength"].Value;
            if (obj != null)
            {
                string len = obj.ToString();
                if (string.Compare(len, "max", true) == 0)
                {
                    return -1;
                }
                else
                {
                    int max_len = Int32.Parse(len);
                    return max_len;
                }
            }
            else
            {
                return 0;
            }
        }

No comments:

Post a Comment