title: NHibernate tracking entity and collection changes
body: <p>I have a service layer returning a collection of entities :</p>
  
  <pre>
  <code>
  /// &lt;summary&gt;
  /// Returns list of all existing accounts.
  /// &lt;/summary&gt;
  IList&lt;Account&gt; GetAllAccounts();
  </code>
  </pre>
  
  <p>This is called on UI layer to get IList collection and bind it to UI via IBindingList :</p>
  
  <pre>
  <code>
  public BindingList&lt;Account&gt; Accounts
  {
     get; 
     private set;
  }
  
  public void LoadAccounts()
  {
     var service = IoC.Resolve&lt;IAccountService&gt;();
     Accounts = new BindingList&lt;Account&gt;(service.GetAllAccounts());
  }
  </code>
  </pre>
  
  <p>Then UI changes the the IBindingList collection (adding, deleting and editing entities), so at some point (before saving) we have a collection that has edited, deleted and new entities. How can I save this collection in a way to avoid unnecessary updates (do not update entities that are not changed). When I do the following, an Insert / Update / Delete statement is ran for ALL items in the collection:</p>
  
  <p>on UI :</p>
  
  <pre>
  <code>
  public void Save()
  {
     var accountService = IoC.Resolve();
     accountService.Update(Accounts);
  }
  </pre>
  
  <p></code></p>
  
  <p>on Service Layer:</p>
  
  <pre>
  <code>
  public void Update(IList&lt;Account&gt; accounts)
  {
      if (accounts == null || accounts.Count == 0)
          return;
  
      using (UnitOfWork.Start())
      using (var session = UnitOfWork.CurrentSession)
      using (var tx = session.BeginTransaction())
      {
          foreach (var acc in accounts)
          {
              if (acc.AccountId == 0)
              {
                  session.Save(acc);
              }
              else
              {
                  session.Update(acc);
              }
          }
  
          tx.Commit();
      }            
  }
  </code>
  </pre>
  
  <p>Note that entities are some POCO classes. Is there any way to know if a collection has changes, or an easy way to find if the entity is dirty (HasChanges or IsDirty kinda thing).</p>