get length of a field

Discussion of open issues, suggestions and bugs regarding LinqConnect – Devart's LINQ to SQL compatible ORM
Post Reply
paul.-b
Posts: 5
Joined: Mon 26 Oct 2009 13:51

get length of a field

Post by paul.-b » Mon 26 Oct 2009 14:06

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

AndreyR
Devart Team
Posts: 2919
Joined: Mon 07 Jul 2008 13:16

Post by AndreyR » Tue 27 Oct 2009 11:08

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.

paul.-b
Posts: 5
Joined: Mon 26 Oct 2009 13:51

Post by paul.-b » Wed 28 Oct 2009 09:30

thank you!
the two last propisitions works great for me!

Paul

Post Reply