C#–Get EDMX Property Names and Class Names of Entities

This is a short tip to get the property name sand class names of entities inside an EDMX Context.

For eg: you have context name as MyContext and you have mapped 2 tables Article  and Person

The property names will be: Articles, People (getting pluralized)

The class names will be still: Article, Person

Please let me know any queries you have.

code to get property names:

        private void button1_Click(object sender, EventArgs e)
        {
            listBox.DataSource = GetPropertyNames(typeof(MyContext));
        }

        public IList<string> GetPropertyNames(Type type)
        {
            return type.GetProperties().Where(p => (p.PropertyType.Name  == "ObjectSet`1") && (p.PropertyType.GetGenericArguments().Count() == 1)).Select(p => p.Name).ToList();
 }

code to get class names:

        private void button2_Click(object sender, EventArgs e)
        {
            listBox.DataSource = GetClassNames(typeof(MyContext ));
        }

        private object GetClassNames(Type type)
        {
            return type.GetProperties().Where(p => (p.PropertyType.Name == "ObjectSet`1") && (p.PropertyType.GetGenericArguments().Count() == 1)).Select(p => p.PropertyType.GetGenericArguments().First().Name).ToList();
         }

Leave a Reply

Your email address will not be published. Required fields are marked *