Search code examples
c#entity-frameworkdomain-driven-designconstantsasp.net-mvc-viewmodel

Replicate property size from domain to fluent api and viewmodel


Do you thinks is it a good idea...

I want to replicate my properties max and min length from the domain to the rest of the application.

For example I have my Customer entity, CustomerConfiguration (for entity framework), and CustomerViewModel.

I have to define customer's name max length in fluent api, then data annotation on ViewModel. If I decide to change the size, I have to change in all places. I thought about define it in a constant in the domain class like:

Code example

  public class Customer {
  .....
  public const int Name_Max = 30;
  public string Name { get; set; }
 .......

public class CustomerConfig.....

 this.Property(e => e.Name).HasMaxLength(Customer.Name_Max);

.....

public class CustomerViewModel {
 ......

 [StringLength(Customer.Name_Max)]
 public string Name { get;set;} ....

Is it a good idea or is there some recommendation against this kind of "replication"?


Solution

  • I see no problem in your approach, on the contrary, we use this model in all company projects in which I work.

    One thing I would do in your model would be use the always-valid entity principle. It will make your life much easier.

    Using this principle you can ensure that your entity is always in a valid state.

    In this case, the setters methods of your properties would do something like:

    public class Customer
    {
        public const int Name_Max = 30;
    
        private string name;
    
        public string Name
        {
            get { return name; }
            set
            {
                if (value != null && value.Length > Name_Max)
                    throw new ArgumentException();
    
                name = value;
            }
        }
    }
    

    See: Validation in Domain-Driven Design (DDD)