How to define ntext fields using Code-First in .NET MVC3 and SQL CE4

Posted on Saturday, 18 June 2011 by nestor in How To

When defining our model using POCO classes, we just use string for all our string model properties that later are created as nvarchar fields in the database. String types max length is 4,000 characters, so, what if I need something longer, for example for a blog content field? Then, we need ntext.

Defining and working with ntext fields It's not quite straight forward, and was not easy to find a solution, so we want to share it here. Let's look at the below simplified POCO class for a blog, where the BlogContent property must be of type ntext to allow content longer than 4,000 chars.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace CloudOne.Models
{
	public class Blog
	{
		public int BlogID { get; set; }
		public int CategoryID { get; set; }
		[MaxLength(70)]
		[Required]
		public string BlogTitle { get; set; }
		[Column(TypeName="ntext")]
		[MaxLength]
		public string BlogContent { get; set; }
	}
}

In order to create a ntext in the database, and allow model validation actually know the string lenght can be more than 4,000 characters we had to use these two items:

  1. [Column(TypeName="ntext")]. This will tell Code-First to generate a ntext field in the database.
  2. [MaxLength]. By using the default constructor, it will take the max length of the database field, instead of guessing max length for a string,which is 4,000. If this is missing or your put like [MaxLength(8000)], model validation will raise errors saying "string max length is 4,000 characters".
Hope this can save your time.


Comments

(2) comments | Post a comment

Rick
#1 Rick on 6/4/2012 1:49:56 PM said:
Thank you much, wish I would have found this earlier hehe.
Lance
#2 Lance on 5/21/2013 4:53:28 PM said:
Nice, this just solved it for me. Thanks for the reference.

Post a comment

*
*
*