Page 1 of 1

get length of a field

Posted: Mon 26 Oct 2009 14:06
by paul.-b
Hello,
I need to get the length of a field to limit the size of the user input to the spezific length of the field.
example

context = new Sivasdatacontext();
var query = from it in context.Parts
select it;

Parts comes with Name i need to know which length this column has in the DB
How can I do this?

thx
Paul

Posted: Tue 27 Oct 2009 11:08
by AndreyR
I am not aware of the way to achieve this using only LINQ to SQL.
In fact, there are two opportunities.
First is to query the database using ADO.NET code and find out the length of the column by executing
Reader.GetSchemaTable() and inspecting the MaxLength property of the necessary column.
The second approach does not query the database. You can use reflection to obtain the attributes for the Name column
and then parse the string value of the DbType attribute to find the maximum length, as it is described here:
http://www.codeproject.com/KB/cs/LinqCo ... ricks.aspx
One more approach is to use DataContext's MetaTypes, like in the following code sample:

Code: Select all

      DataContext1.DataContext1 dc = new DataContext1.DataContext1();
      var q = dc.Mapping.GetTables();
      foreach (MetaTable table in q) 
        foreach (MetaDataMember member in table.RowType.DataMembers) {
          string typeToParse = null;
          if(member.Type == typeof(string))
            typeToParse = member.DbType;
        }

After obtaining the typeToParse string you can trim it and use int.Parse to obtain the MaxLength.

Posted: Wed 28 Oct 2009 09:30
by paul.-b
thank you!
the two last propisitions works great for me!

Paul