如何使用反射从dbcontext获取DBSET <SomeClass>(EF)?[英] How to get DbSet<SomeClass> (EF) from the dbContext using reflection?

本文是小编为大家收集整理的关于如何使用反射从dbcontext获取DBSET <SomeClass>(EF)?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

假设我有

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

我现在有dbset的propertyinfo

我现在要做的是以某种方式迭代(例如,转换为列表),并从表中的每一行获取值.

想象我可以做到这一点:

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

从这里我知道如何进一步钻探和访问属性(使用与上述相同的原理)

推荐答案

dbset同时实现IEnumerable和IEnumerable<T>,,所以类似:

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

大卫

本文地址:https://www.itbaoku.cn/post/1556760.html

问题描述

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)

推荐答案

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