如何获取DbSet< SomeClass> (EF)从dbContext使用反射? [英] How to get DbSet<SomeClass> (EF) from the dbContext using reflection?
本文介绍了如何获取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同时实现了IEnumerable
和IEnumerable<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();
}
}
}
}
大卫
这篇关于如何获取DbSet< SomeClass> (EF)从dbContext使用反射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文