James123
James123

Reputation: 11672

How to get Entity and its properties and types using table name in EF6

I am trying read entity properties and their types using table name in EF6. for example

public partial class ContextEntities : DbContext
{
    public virtual DbSet<tblNote> tblNotes { get; set; }
}

public partial class tblNote
{
    public int intNoteID { get; set; }
    public string strLoanNumber { get; set; }
}

I have entity name called "tblNote" in a string. by using this table name I want to get tblNote entity and its properties and types.

So I did like this

List<Reflection.PropertyInfo> props = new List<Reflection.PropertyInfo>();

PropertyInfo entityProperty = contextEntities.GetType().GetProperties().
                              Where(t => t.Name == "tblNote").Single();
if ((entityProperty != null))
    props.Add(entityProperty); 

This is not working. I am only getting contextEntities properties. How to do that?

Upvotes: 0

Views: 4002

Answers (1)

Dennis
Dennis

Reputation: 37800

Use this query:

        var tblNoteProperties = contextEntities
            .GetType()
            .GetProperties()
            .Where(p =>
                p.PropertyType.IsGenericType &&
                p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
            .Select(p => p.PropertyType.GetGenericArguments()[0])
            .Where(t => t.Name == "tblNote")
            .SelectMany(t => t.GetProperties())
            .ToArray();

Note, that model could be built dynamically, without declaring DbSet<T> properties on DbContext-derived type. In this case you should use EDM to explore entity types and their properties.

Upvotes: 5

Related Questions