Ideally, you should have a clear separation between data models (generated by EF) and view models (used for binding). Therefore, you should check the user data against the definition of the presentation model, and not the definition of the data model.
In MVC the MaxLength attribute is not intended to confirm the maximum allowable input; StringLength is a validation attribute, as described here .
In your particular case:
// this is the data model public class Sensor { public int Id { get; set; } [Required] [MaxLength(40)] public string Name { get; set; } } // this is the data model public class SensorViewModel { public int Id { get; set; } [Required] [StringLength(8)] public string Name { get; set; } }
If MVC used, SensorViewModel will be your @model .
To easily transfer data between Sensor and SensorViewModel , you can use the auto-tuning library. For instance. AutoMapper
If you are not using MVC , there is an alternative to WPF and Windows Forms . In short, you can avoid the code of a simple validation template using attributes.
source share