Esempio n. 1
0
        /// <summary>
        /// Assign primary identifier to newely created entity
        /// </summary>
        /// <param name="entity">Entity instance</param>
        protected virtual void AssignPrimaryIdentifier(TEntity entity)
        {
            //Validazione argomenti
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            //Se è un'entità moderna, genero un GUID
            IModernEntity modern = entity as IModernEntity;

            if (modern != null)
            {
                //Assegno il guid generato
                modern.Id = Guid.NewGuid().ToString("D");
                return;
            }

            //Se è un'entità classica con intero
            IEntity <int> classic = entity as IEntity <int>;

            if (classic != null)
            {
                //Genero il nuovo id utilizzando il massimo già presente ed aggiungendo 1
                int?max = MockedEntities.Count == 0
                    ? 0
                    : MockedEntities
                          .Cast <IEntity <int> >()
                          .Max(e => e.Id);

                //Se trovo un max nullo, emetto eccezione
                if (max == null)
                {
                    throw new InvalidProgramException("Found entity with invalid id.");
                }

                //Incremento il massimo di uno ed assegno
                classic.Id = max + 1;
                return;
            }

            //in tutti gli altri casi emetto eccezione perchè non è una casistica implementata
            throw new NotSupportedException("Automatic assigment of primary identifier is only available " +
                                            "for entities that implements 'IModernEntity' or 'IEntity<int>'; please override this method " +
                                            "in order to provide a custom generator for primary identifier based on your needs");
        }
        /// <summary>
        /// Assign primary identifier to newely created entity
        /// </summary>
        /// <param name="entity">Entity instance</param>
        protected virtual void AssignPrimaryIdentifier(TEntity entity)
        {
            //Validazione argomenti
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            //Se è un'entità moderna, genero un GUID
            IModernEntity modern = entity as IModernEntity;

            if (modern != null)
            {
                //Assegno il guid generato
                modern.Id = Guid.NewGuid().ToString("D");
                return;
            }

            //Se è un identificatore con chiave numerica
            //non faccio nulla perchè sarà il database
            //ad assicurarsi di generare l'id e idratare l'entità
            return;
        }