tags:

views:

1002

answers:

4

I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user.

I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please.

+1  A: 

This blog post seems to be exactly what you need.

Greg Hurlman
A: 

Thanks. Actually both of these answers seem to work. Unfortunately, they seem to look at the Linq attributes generated when the code-generation was done. Although that would seem to be the right thing to do, in my situation we sell software products and occasionally the customer will expand some columns lengths to accommodate their data. Thus, the length of the field as reported using this technique may not always reflect the true length of the underlying data column. Ah well, not Linq to SQL's fault, is it? :)

Thanks for the quick answers!

jwalkerjr
+1  A: 

If you need to know the exact column length you can resort to the System.Data classes themselves. Something a bit like this:

var context = new DataContextFromSomewhere();
var connection = context.Connection;
var command = connection.CreateCommand( "SELECT TOP 1 * FROM TableImInterestedIn" );
var reader = command.ExecuteReader();
var table = reader.GetSchemaTable();

foreach( var column in table.Columns )
{
    Console.WriteLine( "Length: {0}", column.MaxLength );

}
Paul Alexander