title: c# manage progressive identity on domain entity in a client application
body: <p>i have this problem modelling one of my entities:</p>
  
  <ol>
  <li>My entity must have a mandatory ID field that user use to recognize single object</li>
  <li>User don't want to manual enter ID but it must be generate by Application incrementing by 1 every time</li>
  <li>Appllication resides only on clients machine, on server there is only the db</li>
  </ol>
  
  <p>According to 1. I create Id field as mandatory (and not nullable), in this way it must be provided to create an instance but how can program know which ID has to use?</p>
  
  <p>Ideally i have to query db to get max id, add 1 and use this value but how can do it? To mee it seem a matter of my domain object, and i want to isolate domain layer from data access layer so i cant call directly repository from by entity.</p>
  
  <p>Possible solutions:</p>
  
  <ol>
  <li>I look to Interlocked.Increment but how can use it if any user can create a new instance on his client?</li>
  <li>Move the logic to Application Logic layer: there i can call the repository, get the ID, create the class and call repository to save class. in this way a move a domain logic (the incremental id is a specific user request) out of domain layer</li>
  <li>Define repository interface in Domain Layer, call the interface in constructor method of my entity. All doing with dependecy injection, but how? I use ninject in my bootstrapper and all references goes from top to down, how can i revert it for domain layer making it call a superior layer avoiding service locator antipattern (otherwise a can simply write NinjectKernel.Get() in my ctor)</li>
  <li>i found <a href="https://stackoverflow.com/questions/21452984/setting-the-identity-of-a-domain-entity">this article</a> and it's interesting but he use my solution in a bad way (without interface) and don't define the field as mandatory so he can create a new instance withoud specify id</li>
  </ol>
  
  <p>Are there a better solutions?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>some code to better explain tha case:</p>
  
  <pre><code>Public MyClass {
   public int Id{get;set;}
   .....
  
   public MyClass(int id){
    if(id != null)
     this.Id = id;
    else
     throw (new ArgumentException)
  
    .....
   }
  }
  </code></pre>
  
  <p>So i cant do <code>MyClass mc = new MyClass(null);</code>
  but i need to have the id before</p>
  
  <p>in Data Access Layer i use NHibernate and have Uow / Repository pattern</p>
  
  <p>after i can get a valid ID a can write</p>
  
  <pre><code>UnitOfWork.MyClassRepository.Add(mc);
  </code></pre>