问题描述
假设我有
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(); } } } }
大卫
问题描述
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
相关问答