Ilhan
Ilhan

Reputation: 1331

How to get DbSet<SomeClass> (EF) from the dbContext using reflection?

Let's say that I have

DBContext principal = new DBContext();
var x = principal.GetType().GetProperty("SomeClass").GetType();

I now have the PropertyInfo of DbSet< SomeClass >

What I'm trying to do now is somehow iterate (convert to list for example) and get the values from each row in the table.

imagine I could do this:

x[0] // would be the 0th entery in DbSet<SomeClass>, the first row aka of type SomeClass

From here I would know how to further drill down and access properties (using the same principle as above)

Upvotes: 4

Views: 6355

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89091

DbSet implements both IEnumerable and IEnumerable<T>, so something like:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace efAW
{
    class Program
    {

        static IEnumerable GetAllMembers(DbContext db, string dbSetName)
        {
            var pi = db.GetType().GetProperty(dbSetName);
            return (IEnumerable)pi.GetValue(db);
        }
        static void Main(string[] args)
        {
            using (var db = new aw())
            {
                var customers = GetAllMembers(db, "Customers").OfType<Customer>().ToList();
            }
        }
    }
}

David

Upvotes: 6

Related Questions