How to get DbSet (EF) from the dbContex

2019-07-17 09:00发布

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)

1条回答
男人必须洒脱
2楼-- · 2019-07-17 09:26

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

查看更多
登录 后发表回答