简体   繁体   中英

How to get a list of the field names in a table in EF 5

I have my entities defined as follows,

[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; }
    }
}

Some of the fields have an attribute called DoNotAudit .

I need to be able to get a list of the fields in the table that do not have that DoNotAudit attribute.

I tried the following, but it doesn't work. Any ideas ?

  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;

        }

Updated query

 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();

table is already the type you need, so table.GetType() is not correct. Just use table.GetProperties() as below:

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

EDIT: table is of type IQueriable<Type> , so a call to .First() is needed to get the actual object.

EDIT Updated Linq query to ignore all virtual properties and properties marked DoNotAudit .

Reflection of the Type typeof(Poco).GetProperties() can lead to different results to what is actually tracked in EF. EF will ignore some types, some types may have Ignore annotations. Complex Types need special attention.

If you want the EF view of the model, then access the MetadataWorkspace .

Some basic dump Metadata to debug console code...

   [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

                }
            }
        }

or via the 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM