如何获取EF 5中表格中的字段名称列表

时间:2014-01-19 01:44:13

标签: c# entity-framework asp.net-mvc-4 entity-framework-5

我的实体定义如下,

[Table("AuditZone")]
    public class AuditZone
    {
        public AuditZone()
        {
            AuditZoneUploadedCOESDetails = new List<UploadedCOESDetails>();
            AuditZonePostcode = new List<Postcodes>();
        }

        [Key]
        [DoNotAudit]
        public int Id { get; set; }
        public string Description { get; set; }     
        public bool Valid { get; set; }

        [DoNotAudit]
        public DateTime CreatedDate { get; set; }
        [DoNotAudit]
        public int? CreatedBy { get; set; }
        [DoNotAudit]
        public DateTime? ModifiedDate { get; set; }
        [DoNotAudit]
        public int? ModifiedBy { get; set; }

        public virtual UserProfile CreatedByUser { get; set; }
        public virtual UserProfile ModifiedByUser { get; set; }

        public virtual ICollection<UploadedCOESDetails> AuditZoneUploadedCOESDetails { get; set; }
        public virtual ICollection<Postcodes> AuditZonePostcode { get; set; }
    }
}

某些字段具有名为DoNotAudit的属性。

我需要能够获得表格中没有DoNotAudit属性的字段列表。

我尝试了以下操作,但它不起作用。有什么想法吗?

  public IEnumerable<string> GetFields(string tableName)
        {


            var table = typeof(AISDbContext).GetProperties().Select(n => n.PropertyType) // here we get all properties of contect class
                             .Where(n => n.Name.Contains("DbSet") && n.IsGenericType) // here we select only DBSet collections
                             .Select(n => n.GetGenericArguments()[0])
                            .Where(n => n.Name == tableName);

            var doNotAuditList = table.GetType()
                                       .GetProperties()
                                       .Where(p => p.GetCustomAttributes(typeof(DoNotAudit), false).Any())
                                       .Select(p => p.Name)
                                       .ToList();
            return doNotAuditList;

        }

更新了查询

 var doNotAuditList = table.First().GetProperties()
                  .Where(p=> p.PropertyType.FindInterfaces(new TypeFilter((t,o) => t == typeof(IEnumerable)), null).Length == 0)
                  .Where(n => n.GetCustomAttributes(true).OfType<DoNotAudit>().FirstOrDefault() == null)
                                       .Select(p => p.Name)
                                       .ToList();

2 个答案:

答案 0 :(得分:0)

table已经是您需要的类型,因此table.GetType()不正确。只需使用table.GetProperties(),如下所示:

        var doNotAuditList = table.First()
                                  .GetProperties()
                                   .Where(p => p.GetCustomAttributes(typeof(DoNotAudit), false).Any() == false
                                   && p.GetGetMethod().IsVirtual == false)
                                  .Select(p => p.Name)
                                  .ToList();

修改 table的类型为IQueriable<Type>,因此需要调用.First()来获取实际对象。

修改 更新了Linq查询以忽略标记为DoNotAudit的所有虚拟属性和属性。

答案 1 :(得分:0)

类型typeof(Poco).GetProperties()的反映可能导致与EF中实际跟踪的内容不同的结果。 EF将忽略某些类型,某些类型可能会忽略注释。 复杂类型需要特别注意。

如果您想要模型的EF视图,请访问MetadataWorkspace

调试控制台代码的一些基本转储元数据......

   [TestMethod]
    public void EFToolsTest() {
    //  http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.dataspace(v=vs.110).aspx
        var context = new YourContext(); // DbContext type
        ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
        MetadataWorkspace workspace = objContext.MetadataWorkspace;

        var xyz = workspace.GetItems<EntityType>(DataSpace.SSpace);
        foreach (var ET in xyz) {
            foreach (var sp in ET.Properties) {
                Debug.WriteLine(sp.Name + ":" + sp.MaxLength);// just as an example

                }
            }
        }

或通过DataSpace.OSpace

   public static  void DumpContextManagedTypeProps() {
       var context = new YourContent();
        ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
        MetadataWorkspace workspace = objContext.MetadataWorkspace;
        IEnumerable<EntityType> managedTypes = workspace.GetItems<EntityType>(DataSpace.OSpace);
        foreach (var managedType in managedTypes.Where(mt=>mt.Ful) {
        Console.WriteLine(managedType.FullName);
        // propertyInfo and other useful info is available....
        foreach ( var p in managedType.Properties) {
                Console.WriteLine(p.Name );
            }
        }
        return result;
    }