获取所有模型类型 [英] Get all model types
问题描述
如何获取属于模型的实体类型列表,所以我可以测试该模型是否与该实体类型一起使用?
How can I get a list of entity types that are part of the model, so I can test that the model actually works with that entity type?
var dcx = new MyDbContext();
var lst = new List<Type>();
//populate the list here somehow
//...
foreach (var t in lst) {
var set = dcx.Set(t); //I'm trying to avoid an exception here
try {
var test = set.FirstOrDefault();
} catch (Exception ex) {
Console.WriteLine("{0} has an error", t);
}
}
注意:完全可以查询 dcx.Set(t)
即使在 MyDbContext $ c $之间没有相应的
DbSet
属性C>;因此,通过对 MyDbContext
的属性进行反复迭代是不够的,其返回类型的通用定义是 DbSet
或甚至 IDbSet< T>
。
NB: It is perfectly possible to query dcx.Set(t)
even if there is no corresponding DbSet
property on MyDbContext
; therefore it's not enough to iterate via reflection over the properties of MyDbContext
whose return type's generic definition is DbSet<T>
or even IDbSet<T>
.
推荐答案
感谢< a href =https://stackoverflow.com/questions/33928716/get-all-model-types?noredirect=1#comment55710171_33928716> @GertArnold的评论,我现在使用以下内容:
Thanks to the link in @GertArnold 's comment, I am now using the following:
var dcx = new MyDbContext();
var objContext = ((IObjectContextAdapter)dcx).ObjectContext;
var types = db.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.OSpace).Select(x => Type.GetType(x.FullName));
foreach (var t in lst) {
...
这篇关于获取所有模型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!