My client is using c#, EF6.0 database-first, and webforms. I want to validate for the max length of a textbox entry in an aspx form. I don't want to hardcode the max-length client-side or server-side, instead I want to retrieve it from the EF6.0 entity model so that it matches the length of the underlying database-first field. The field is an nvarchar(40). (If I was working in a 'code-first' scenario I would try using validation annotations, but this doesn't seem possible in 'database-first').
How can I do the validation based on the underlying database-first field length?
I found a good solution. Since asp.net 4.5 it is possible to use Data-Annotation attributes with WebForms and Entity Frameworks. Specifically:
using System.ComponentModel.DataAnnotations;
namespace Diary.DataAccess.Model
{
// Accommodate EF database-first regeneration (required for webforms)
[MetadataType(typeof(UserDetailMetaData))]
public partial class UserDetail
{
}
// Add the Data-Annotation attribute to the Title model-property.
public class UserDetailMetaData
{
[MaxLength(40, ErrorMessage="Title must not be more than 40 characters long.")]
public string Title { get; set; }
}
}
(This doesn't retrieve the constant from the database-first metadata, but does keep it in one place.)