Hello @Saifullah ,
The following repository contains code that may assist with this task. Code is broken between a windows form and class project. The frontend need not be windows forms, could be web or WPF etc.
What it doesn't provide
- Line numbers
- Graphical representations
- Does not cover all versions of Entity Framework.
- No guarantees the presented code will be for you.
What it does provide, an excellent foundation for getting started with many hidden gems if those interested take time to run the code under the debugger and examine what is available.
Generics and asynchronous techniques are used.
Here is an example for getting model names. A ListBox is populated with model names
public static async Task<List<string>> GeModelNames<TContext>() where TContext : DbContext
{
return await Task.Run(async () =>
{
await Task.Delay(0);
ObjectContext objectContext;
using (TContext context = Activator.CreateInstance<TContext>())
{
objectContext = ((IObjectContextAdapter)context).ObjectContext;
}
var container = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);
return container.EntitySets.Select(item => item.Name).OrderBy(x => x).ToList();
});
}
To get navigation properties for example, the code below does this by taking the selected text (model name) from the ListBox and converts the string to a type. Note here I used strings for namespace as the EF code is not in the same project.
Type type = Type.GetType($"NorthWindForEntityFramework6.{ModelNamesListBox.Text}, NorthWindForEntityFramework6");
NavigationListBox.DataSource = EntityCrawler.GetNavigationProperties(type);
Which uses the following method to get the navigation properties or an empty array if there are none.
public static string[] GetNavigationProperties(Type entityType)
{
return entityType.GetProperties()
.Where(p => (typeof(IEnumerable).IsAssignableFrom(p.PropertyType) && p.PropertyType != typeof(string)) || p.PropertyType.Namespace == entityType.Namespace)
.Select(p => p.Name)
.ToArray();
}
Then to get a twist, there is a similar method returning different details.
public static ReadOnlyMetadataCollection<NavigationProperty> GetNavigationProperties<TEntity, TContext>() where TContext : DbContext
{
ObjectContext objectContext;
using (TContext context = Activator.CreateInstance<TContext>())
{
objectContext = ((IObjectContextAdapter)context).ObjectContext;
}
var container = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace);
var navigationProperties = ((EntityType)container.BaseEntitySets.First(bes => bes.ElementType.Name == typeof(TEntity).Name).ElementType).NavigationProperties;
return navigationProperties;
}
In closing, there is no one perfect solution is my guess and if there are third party libraries you can know that there is a great amount of time put into them.
Hopefully you can find some use of the code in the repository.