Limiting LINQ String Field Lengths

by Mark Wiseman on October 9th, 2009 | Posted in Revium Sandbox | Comment on this entry

We recently had an issue where a string value in our LINQ object was changed and became longer than the database field it represented. Whenever we tried to apply the changes to the database we would get an error. Now, i know that the correct solution is to implement the proper checks earlier on in the change cycle but it just erks me a little that the LINQ object doesn’t say: “Hey, you, coder… you can’t set a value that long to this property because it’s too long” when it clearly know what it is.

If you look at the definition of one of the Columns you will see that it has an Attribute of type ColumnAttribute. This attribute stores all the information required to map the field back to the database.

[Column(Storage="_AColumn", DbType="VarChar(50) NOT NULL", CanBeNull=false)]
public string AColumn
{
	get
	{
		return this._AColumn;
	}
	set
	{
		if ((this._AColumn != value))
		{
			this.OnNameChanging(value);
			this.SendPropertyChanging();
			this._AColumn = value;
			this.SendPropertyChanged("AColumn");
			this.OnNameChanged();
		}
	}
}

We can clearly see from this that our LINQ object does know the column length so i decide to write a routine to trim off the excess fat. The routine, when we SubmitChanges during OnValidate, uses reflection to get the field length and trim the value to fit. Now this could also easily be used to notify you of fields that are too long as well.

To do this we have to extend our LINQ Data Context. The actual DataContext’s name is MyDataContext. So we will name the extended one MyDataContext2… creative huh? We then enumerate through the class’ Properties and then each Properties Column attributes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.Reflection;
using System.Data.Linq.Mapping;

public class MyDataContext2 : MyDataContextDataContext
{
	public MyDataContext2 ()
		: base(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)
	{
	}
}    

public partial class MyTable
{
	partial void OnValidate(System.Data.Linq.ChangeAction action)
	{
		//Trim all the string fields so that we don't get DB errors.

		//Check each property in the table
		foreach (MemberInfo memInfo in (typeof(MyTable)).GetProperties())
		{
			//Only Loop through Column attributes
			foreach (object attribute in memInfo.GetCustomAttributes(typeof(ColumnAttribute), true))
			{
				ColumnAttribute ca = (ColumnAttribute)attribute;
				PropertyInfo propInfo = (PropertyInfo)memInfo;

				//Only limit varchar values
				if (ca.DbType.ToLower().Contains("varchar"))
				{
					string dbType = ca.DbType.ToLower();
					string varchar = "varchar(";
					int noStart = dbType.ToLower().IndexOf(varchar) + varchar.Length;
					int noEnd = dbType.IndexOf(")", noStart);

					string sLength = dbType.Substring(noStart, noEnd - noStart); //strings are stored as VarChar(XXX) NOT NULL

					int iLength = 0;
					int.TryParse(sLength, out iLength);

					string value = string.Empty;

					if (propInfo.GetValue(this, null) != null)
						value = propInfo.GetValue(this, null).ToString();

					if (value.Length > iLength)
						propInfo.SetValue(this, value.Substring(0, iLength), null);
				}
			}
		}
	}
}

Related posts:

  1. Linq to SQL select and update oddity
  2. Linq – SubmitChanges does not work
  3. CSV parsing – the easy way!
  4. Asp.Net MVC convert View to Word Document
  5. Sharepoint – Getting Photos from People and Groups

« Javascript Window Tiling

Office 2007 and Zip files »

Leave a Reply

Click here to cancel reply.

Recent Articles

  • Return of the daily sites
  • Collaborating with Government
  • Ya-bing-ooo!! Yahoo search is dead long live the Bing.
  • Social Media – Good For Some
  • 10 Tips for user acceptance testing of web applications
  • Popular Content Management Systems
  • ASP.NET MVC [HandleError] and logging
  • VMWare hard lessons

Twitter

  • Collaborating with Government: Revium is actively involved in the Federal Government’s R&D program for tax concess... http://bit.ly/9D7Vc6 6 days ago
  • 45 Free Applications For Web Designers & Developers http://www.noupe.com/tools/45-free-applications-for-designers-and-developers.html 1 week ago
  • In most watch advertisements the time displayed on the timepiece is 10:10 because then the arms frame the brand of the watch. 1 week ago
  • More updates...

Revium Logo

  • Home
  • About
  • Expertise
  • Showcase
  • Contact

  • news
  • blog
  • sandbox
  • twitter
  • facebook
  • rss
Bookmark and Share

We are Revium, hear us roar!

The news.

31 Aug

Collaborating with Government

Revium is actively involved in the Federal Government’s R&D program for tax concessions to develop our in-house products that we are looking to take…

Continue reading
View archive

The blog.

01 Sep

Return of the daily sites

Years ago I used to have a morning routine of checking a select few websites I came across. For one reason or another I…

Continue reading
View archive

The sandbox.

20 Aug

Ya-bing-ooo!! Yahoo search is dead long live the Bing.

Ya-bing-oo!! Yahoo search is dead long live the Bing In July 2010 Yahoo had started testing Bing powered search they routed 25% of their search…

Continue reading
View archive

eNewsletter.

 

© Copyright 2010. All Rights Reserved.

Revium Pty Ltd

e / info@revium.com.au t / Work +61 3 9429 2000

Find us: web development, seo

Disclaimer and privacy Revium Pty Ltd

10 Harvey Street
Richmond, Victoria, 3121 Australia
View map

Logo Partner MicrosoftLogo Partner KenticoLogo Partner IiaLogo Partner Iia RibLogo Partner Acs