How to get column names from LINQ model?

I am looking to get a list of column names returned from a model. Does anyone know how this will be done, any help would be greatly appreciated.

Code example:

var project = db.Projects.Single(p => p.ProjectID.Equals(Id)); 

This code will return a Projects object, how can I get a list of all the column names in this model.

thanks

+3
source share
7 answers

Sorry, I have no experience with LINQ.

This is purely based on MSDN browsing.

DataContext has a Mapping property that returns an instance of MetaModel .
MetaModel has a GetMetaType that accepts a Type . In your case, it could be typeof(Project) .
GetMetaType returns a MetaType that has a GetDataMember method that accepts MemberInfo . You will need to use reflection in the Projects object to get the MemberInfo object.
The MetaDataMember instance returned by GetDataMember should have everything you need.

I hope I'm a little in the right direction (looking purely at MSDN and going through)

+1
source

It would be nice to have as an extension method:

 public static class LinqExtensions { public static ReadOnlyCollection<MetaDataMember> ColumnNames<TEntity> (this DataContext source) { return source.Mapping.MappingSource.GetModel (typeof (DataContext)).GetMetaType (typeof (TEntity)).DataMembers; } } 

Example:

 var columnNames = myDataContext.ColumnNames<Orders> (); 
+15
source

Thank you guys, you started me on the right track. I found a solution with the following code. Then I can iterate through the DataMembers and pull out their individual properties, such as name, type, etc.

 var db = new GMPDataContext(); var columnNames = db.Mapping.MappingSource .GetModel(typeof(GMPDataContext)) .GetMetaType(typeof(Project)) .DataMembers; 
+6
source

The shell of your projects will have a set of properties, each of which has the [Column] attribute. Therefore, simply use reflection to list properties with this attribute.

+3
source

Using the Todd Smiths (+1) solution, you get all the properties (included entities, etc.). To filter out all properties other than columns, this will result in a trick:

 var columnNames = db.ColumnNames<Orders>().Where(n => n.Member.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).FirstOrDefault() != null).Select(n => n.Name); 
+2
source

Your columns should be mapped as properties in your project model. I am not sure if the basic database structure can be obtained using LINQ to SQL. The whole LINQ to SQL point is database abstraction.

0
source

Here's another way:

  public string[] GetColumnNames() { var propnames = GetPropertyNames(_context.Users); return propnames.ToArray(); } static IEnumerable<string> GetPropertyNames<T>(IEnumerable<T> lst) { foreach (var pi in typeof(T).GetProperties()) { yield return pi.Name; } } 
0
source

All Articles