Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 557
Ilhan Avatar asked Sep 16 '25 10:09

Ilhan


1 Answers

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

like image 62
David Browne - Microsoft Avatar answered Sep 18 '25 08:09

David Browne - Microsoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!