Validate entry length based on database-first entity model

asp.net c# ef-database-first entity-framework-6 webforms

Question

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?

1
1
7/7/2015 6:07:10 PM

Popular Answer

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.)

0
7/10/2015 12:26:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow