Can I get the column name as a string when using LINQ and SqlMetal?

  • Thread starter Thread starter Big Daddy
  • Start date Start date
B

Big Daddy

For example, if I have a DB table called DownloadPoints with a column
named DownloadPointNo, then SqlMetal will create a file with a class
called DownloadPoints with an accessor named DownloadPointNo. I would
like the object to be able to pass me the string "DownloadPointNo".
For example, the code could be something like:

DownloadPoints dp = new DownloadPoints();
string colName = dp.DownloadPointNo.ColumnName;

Or I could write a helper function that would find it like this:

DownloadPoints dp = new DownloadPoints();
string colName = HelperFunction(dp.DownloadPointNo);

Is there any way to do this?

thanks in advance,
John
 
Big said:
For example, if I have a DB table called DownloadPoints with a column
named DownloadPointNo, then SqlMetal will create a file with a class
called DownloadPoints with an accessor named DownloadPointNo. I would
like the object to be able to pass me the string "DownloadPointNo".
For example, the code could be something like:

DownloadPoints dp = new DownloadPoints();
string colName = dp.DownloadPointNo.ColumnName;
First of all, if the column name isn't special, then you already know what
it is: it's exactly the same as the name of the property. So whatever you
use to determine the property is what you can use to determine the column name.

For the general case (where the column name might be something that can't be
represented unescaped, like "My Column"), retrieving the ColumnAttribute of
the property will do:

((ColumnAttribute)
typeof(DownloadPoints).GetProperty("DownloadPointNo").GetCustomAttribute(typeof(ColumnAttribute),
false)).Name;

This doesn't just look cumbersome, it actually is, since it uses reflection.
You should strongly consider a properly separated design where you do not
need to know the column name. Use of this knowledge should be restricted to
within your data access layer. SqlMetal generates partial classes, so you
can always add your own members to your DAL classes if you need more. While
such custom members can't be updated automatically in response to changes,
there's dubious value in using LINQ to SQL to begin with if your schema
changes frequently.
 
I've had a similar problem in the past that is sitting and waiting for me to
get back to it. Getting meta data about the table such as column names is
important if you need to build a form dynamically.
 
Back
Top