我正在构建一个MVC 4应用程序。我有一个下拉列表需要显示使用的特定表(实体)..
某些实体具有名为DoNotAUdit
的属性[DoNotAudit]
public class AuditLog
{
public Guid AuditLogId { get; set; }
public int UserId { get; set;}
public DateTime EventDateUTC { get; set; }
public string EventType { get; set; }
public string TableName { get; set; }
public string RecordId { get; set; }
public string ColumnName { get; set; }
public string OriginalValue { get; set; }
public string NewValue { get; set; }
}
虽然其他实体没有该自定义属性。
我只想获得没有该属性的所有实体的列表。
另一个堆栈溢出用户Radenko Zec向我展示了如何获取所有表格(就像我问他的那样)但是现在我需要更多的帮助
要获得他建议的所有表格,
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Data.Entity.Infrastructure;
...
using (dbcontext context = new TestContext())
{
ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
MetadataWorkspace workspace = objContext.MetadataWorkspace;
IEnumerable<EntityType> tables = workspace.GetItems<EntityType>(DataSpace.SSpace);
}
我该怎么做?我首先使用EF 5代码进行配置。
任何帮助都将不胜感激。
答案 0 :(得分:0)
try this
typeof(TestContext).GetProperties().Select(n => n.PropertyType) // here we get all properties of contect class
.Where(n => n.Name.Contais("DbSet") && n.IsGenericType) // here we select only DBSet collections
.Select(n=>n.GetGenericArgumenrs()[0])//Here we access to TEntiy type in DbSet<TEntity>
.Where(n => n.GetCustomAttributes(true).OfType<DoNotAudit>().FirstOrDefault()== null) // here we check for attribute existence
.OrderBy(n=>n.Name) // Here is sorting by Name
.Select(n => n.Name).ToList(); // here we select the names of entity classes