views:

1458

answers:

5

I am looking to get a list of the column names returned from a Model. Anyone know how this would be done, any help would be greatly appreciated.

Example Code:

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

This code would return the Projects object, how would I get a list of all the column names in this Model.

Thanks

A: 

Your columns should be mapped as properties on your Project model. I'm not sure if you can get the underlying database structure when using LINQ to SQL. The entire point of LINQ to SQL is to abstract the database away.

Kyle West
+3  A: 

Your Projects wrapper will have a set of properties each with a [Column] attribute. So just use reflection to enumerate the properties with that attribute.

Todd Smith
I don't understand why so many solutions use reflection. Scott Gu's solution to converting an IQueryable to DataTable uses reflection to build a schema from a table entity decorated with the TableAttribute. I'd rather "SELECT TOP 0 (field1, field2,...) FROM myTable" and execute the datareader as datatable.
dboarman
A: 

I am sorry, I don't have working experience with LINQ.

This is purely based on looking at MSDN.

DataContext has Mapping property (which gives instance of MetaModel)
MetaModel has GetMetaType (which takes a type. in your case it could be typeof(Project))
MetaType has GetDataMmber (which takes a MemberInfo. you will have to use reflection)
MetaDataMember instance should have all the things, you need.

I hope I am somewhat in right direction (purely looking at MSDN & traversing)

shahkalpesh
+2  A: 

Thanks guys, you got me started on the right track. I found my solution with the following code. I can then 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;
tsquillario
Awesome...I'll be using this.
dboarman
+2  A: 

This 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> ();
Todd Smith
@Todd, this is a much better solution than using reflection. :)
dboarman