1

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?

CodeCabbie
  • 3,098
  • 2
  • 19
  • 30

2 Answers2

0

You can create partial classes for your generated POCOs and apply validations there that won't get overwritten when you regenerate: Add data annotations to a class generated by entity framework

Community
  • 1
  • 1
Steve Greene
  • 12,029
  • 1
  • 33
  • 54
0

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

CodeCabbie
  • 3,098
  • 2
  • 19
  • 30
  • 1
    But you still need to hardcode 40 for the max length. I am also looking for a solution that no hardcode on View and Model. In other words, when i changed my database field size to 1000, my code is not affected and run according. Any idea? – sky91 Apr 10 '16 at 08:41
  • Unfortunately you do still need to hardcode the max length which is a problem I still haven't solved. This answer helps a little as it puts the constant in one place (but not very much!). I would be very interested if you have found a way to do it properly / dynamically as you describe in your comment. – CodeCabbie Apr 27 '17 at 10:34
  • Yes, I am still seeking the solution too. I will share the solution while I found it. – sky91 Apr 28 '17 at 07:26