Wednesday, March 27, 2013

Validating Linq to Sql Model

If you have created a Linq to Sql class as your model and need to add validation to it, simply create an interface and add the columns needed to validate.

ILog interface class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
 
namespace Test1.Models
{
    interface ILog
    {
        [Required]
        [RegularExpression(@"(\s|.){1,50}$", ErrorMessage = "Field cannot contain more than 50 characters")]
        string Name { getset; }
 
        [Required]
        [RegularExpression(@"[0-9]*", ErrorMessage = "Field must be an integer")]
        int TableKey { getset; }
 
        [Required]
        [RegularExpression(@"(\s|.){1,50}$", ErrorMessage = "Field cannot contain more than 500 characters")]
        string Value { getset; }
    }
}



Log LinqToSql class:

using Test1.Models;
using System.ComponentModel.DataAnnotations;
 
namespace Log.Model
{
    [MetadataType(typeof(ILog))]
    partial class Log : ILog
    {
    }
}

Simple enough?

For larger models, I suggest creating a ViewModel and handle everything in there...

No comments:

Post a Comment