如何获取DbSet< SomeClass> (EF)从dbContext使用反射?

如何获取DbSet< SomeClass> (EF)从dbContext使用反射?

问题描述:

假设我有

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

我现在有了DbSet的PropertyInfo. SomeClass>

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)

DbSet同时实现了IEnumerableIEnumerable<T>,,例如:

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();
            }
        }
    }
}

大卫