Ejemplo n.º 1
0
        private object SetNextId(object item)
        {
            var idVal = GetId(item);

            if (DbReposetoryIdentityInsertScope.Current != null && _currentDbReposetoryIdentityInsertScope == null)
            {
                _currentDbReposetoryIdentityInsertScope = DbReposetoryIdentityInsertScope.Current;
                _currentDbReposetoryIdentityInsertScope.EnsureTransaction();
            }

            if (_currentDbReposetoryIdentityInsertScope != null)
            {
                if (idVal.Equals(Constraints.PrimaryKey.GetUninitilized()) && !_currentDbReposetoryIdentityInsertScope.RewriteDefaultValues)
                {
                    return(idVal);
                }
                if (!idVal.Equals(Constraints.PrimaryKey.GetUninitilized()))
                {
                    return(idVal);
                }
                lock (LockRoot)
                {
                    var newId = Constraints.PrimaryKey.GetNextValue();
                    _typeInfo.PrimaryKeyProperty.Setter.Invoke(item,
                                                               Convert.ChangeType(newId, _typeInfo.PrimaryKeyProperty.PropertyType));
                    return(newId);
                }
            }

            if (idVal.Equals(Constraints.PrimaryKey.GetUninitilized()))
            {
                lock (LockRoot)
                {
                    var newId = Constraints.PrimaryKey.GetNextValue();
                    _typeInfo.PrimaryKeyProperty.Setter.Invoke(item,
                                                               Convert.ChangeType(newId, _typeInfo.PrimaryKeyProperty.PropertyType));
                    return(newId);
                }
            }

            var exception =
                new InvalidOperationException(string.Format("Cannot insert explicit value for identity column in table '{0}' " +
                                                            "when no IdentityInsertScope exists.", _typeInfo.Name));

            throw exception;
        }