internal override async System.Threading.Tasks.Task BuildValueAsync(DbDataReader reader, CancellationToken cancellationToken)
        {
            if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
            {
                if (TypeConverter.IsNotEntityAndConvertible(resultType))
                {
                    var typeConverter = TypeConverter.For(resultType) ?? TypeConverter.Default;

                    this.Value = (T)typeConverter.ConvertFromDbValue(reader, 0, resultType);
                }
                else
                {
                    var objectInfo = ObjectInfo.For(resultType);

                    this.Value = (T)objectInfo.CreateInstance(reader);
                }

                this.HasValue = true;

                if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    throw new MicroLiteException(ExceptionMessages.Include_SingleRecordExpected);
                }

                if (this.callback != null)
                {
                    this.callback(this);
                }
            }
        }
        internal override void BuildValue(IDataReader reader)
        {
            if (reader.Read())
            {
                if (TypeConverter.IsNotEntityAndConvertible(resultType))
                {
                    var typeConverter = TypeConverter.For(resultType) ?? TypeConverter.Default;

                    this.Value = (T)typeConverter.ConvertFromDbValue(reader, 0, resultType);
                }
                else
                {
                    var objectInfo = ObjectInfo.For(resultType);

                    this.Value = (T)objectInfo.CreateInstance(reader);
                }

                this.HasValue = true;

                if (reader.Read())
                {
                    throw new MicroLiteException(ExceptionMessages.Include_SingleRecordExpected);
                }

                if (this.callback != null)
                {
                    this.callback(this);
                }
            }
        }
        /// <summary>
        /// Invoked after the SqlQuery to insert the record for the instance has been executed.
        /// </summary>
        /// <param name="instance">The instance which has been inserted.</param>
        /// <param name="executeScalarResult">The execute scalar result (the identifier value returned by the database
        /// or null if the identifier is <see cref="IdentifierStrategy" />.Assigned.</param>
        /// <exception cref="ArgumentNullException">Thrown if instance is null or IdentifierStrategy is DbGenerated
        /// and executeScalarResult is null.</exception>
        public void AfterInsert(object instance, object executeScalarResult)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            if (executeScalarResult == null)
            {
                return;
            }

            var objectInfo = ObjectInfo.For(instance.GetType());

            if (objectInfo.TableInfo.IdentifierStrategy != IdentifierStrategy.Assigned)
            {
                if (log.IsDebug)
                {
                    log.Debug(LogMessages.IListener_SettingIdentifierValue, objectInfo.ForType.FullName, executeScalarResult.ToString());
                }

                var propertyType = objectInfo.TableInfo.IdentifierColumn.PropertyInfo.PropertyType;

                if (executeScalarResult.GetType() != propertyType)
                {
                    var converted = Convert.ChangeType(executeScalarResult, propertyType, CultureInfo.InvariantCulture);

                    objectInfo.SetIdentifierValue(instance, converted);
                }
                else
                {
                    objectInfo.SetIdentifierValue(instance, executeScalarResult);
                }
            }
        }
Exemple #4
0
        internal override async System.Threading.Tasks.Task BuildValueAsync(DbDataReader reader, CancellationToken cancellationToken)
        {
            if (TypeConverter.IsNotEntityAndConvertible(resultType))
            {
                var typeConverter = TypeConverter.For(resultType) ?? TypeConverter.Default;

                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    var value = (T)typeConverter.ConvertFromDbValue(reader, 0, resultType);

                    this.values.Add(value);
                }
            }
            else
            {
                var objectInfo = ObjectInfo.For(resultType);

                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    var instance = (T)objectInfo.CreateInstance(reader);

                    this.values.Add(instance);
                }
            }

            this.HasValue = this.values.Count > 0;

            if (this.callback != null)
            {
                this.callback(this);
            }
        }
Exemple #5
0
        public void SelectByIdentifierQuery()
        {
            ObjectInfo.MappingConvention = new ConventionMappingConvention(
                UnitTest.GetConventionMappingSettings(IdentifierStrategy.DbGenerated));

            var mockSqlDialect = new Mock <SqlDialect>(SqlCharacters.Empty);

            mockSqlDialect.CallBase = true;

            var identifier = 134875;

            var sqlQuery = mockSqlDialect.Object.BuildSelectSqlQuery(ObjectInfo.For(typeof(Customer)), identifier);

            Assert.Equal("SELECT Created,CreditLimit,DateOfBirth,Id,Name,CustomerStatusId,Updated,Website FROM Sales.Customers WHERE (Id = ?)", sqlQuery.CommandText);
            Assert.Equal(1, sqlQuery.Arguments.Count);

            Assert.Equal(DbType.Int32, sqlQuery.Arguments[0].DbType);
            Assert.Equal(identifier, sqlQuery.Arguments[0].Value);

            // Do a second query to check that the caching doesn't cause a problem.
            identifier = 998866;

            var sqlQuery2 = mockSqlDialect.Object.BuildSelectSqlQuery(ObjectInfo.For(typeof(Customer)), identifier);

            Assert.Equal("SELECT Created,CreditLimit,DateOfBirth,Id,Name,CustomerStatusId,Updated,Website FROM Sales.Customers WHERE (Id = ?)", sqlQuery2.CommandText);
            Assert.Equal(1, sqlQuery2.Arguments.Count);

            Assert.Equal(DbType.Int32, sqlQuery2.Arguments[0].DbType);
            Assert.Equal(identifier, sqlQuery2.Arguments[0].Value);
        }
Exemple #6
0
        public async Task InsertAsync(object instance, CancellationToken cancellationToken)
        {
            this.ThrowIfDisposed();

            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            for (int i = 0; i < this.insertListeners.Count; i++)
            {
                this.insertListeners[i].BeforeInsert(instance);
            }

            var objectInfo = ObjectInfo.For(instance.GetType());

            objectInfo.VerifyInstanceForInsert(instance);

            object identifier = await this.InsertReturningIdentifierAsync(objectInfo, instance, cancellationToken).ConfigureAwait(false);

            for (int i = this.insertListeners.Count - 1; i >= 0; i--)
            {
                this.insertListeners[i].AfterInsert(instance, identifier);
            }
        }
Exemple #7
0
        public bool Delete(object instance)
        {
            this.ThrowIfDisposed();

            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            for (int i = 0; i < this.sessionListeners.DeleteListeners.Count; i++)
            {
                this.sessionListeners.DeleteListeners[i].BeforeDelete(instance);
            }

            var objectInfo = ObjectInfo.For(instance.GetType());

            var identifier = objectInfo.GetIdentifierValue(instance);

            if (objectInfo.IsDefaultIdentifier(identifier))
            {
                throw new MicroLiteException(ExceptionMessages.Session_IdentifierNotSetForDelete);
            }

            var sqlQuery = this.SqlDialect.BuildDeleteSqlQuery(objectInfo, identifier);

            var rowsAffected = this.ExecuteQuery(sqlQuery);

            for (int i = this.sessionListeners.DeleteListeners.Count - 1; i >= 0; i--)
            {
                this.sessionListeners.DeleteListeners[i].AfterDelete(instance, rowsAffected);
            }

            return(rowsAffected == 1);
        }
Exemple #8
0
        public async Task <bool> DeleteAsync(object instance, CancellationToken cancellationToken)
        {
            this.ThrowIfDisposed();

            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            for (int i = 0; i < this.deleteListeners.Count; i++)
            {
                this.deleteListeners[i].BeforeDelete(instance);
            }

            var objectInfo = ObjectInfo.For(instance.GetType());

            var identifier = objectInfo.GetIdentifierValue(instance);

            if (objectInfo.IsDefaultIdentifier(identifier))
            {
                throw new MicroLiteException(ExceptionMessages.Session_IdentifierNotSetForDelete);
            }

            var sqlQuery = this.SqlDialect.BuildDeleteSqlQuery(objectInfo, identifier);

            var rowsAffected = await this.ExecuteQueryAsync(sqlQuery, cancellationToken).ConfigureAwait(false);

            for (int i = this.deleteListeners.Count - 1; i >= 0; i--)
            {
                this.deleteListeners[i].AfterDelete(instance, rowsAffected);
            }

            return(rowsAffected == 1);
        }
Exemple #9
0
        internal override async Task BuildValueAsync(DbDataReader reader, CancellationToken cancellationToken)
        {
            if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
            {
                if (TypeConverter.IsNotEntityAndConvertible(s_resultType))
                {
                    ITypeConverter typeConverter = TypeConverter.For(s_resultType) ?? TypeConverter.Default;

                    Value = (T)typeConverter.ConvertFromDbValue(reader, 0, s_resultType);
                }
                else
                {
                    IObjectInfo objectInfo = ObjectInfo.For(s_resultType);

                    Value = (T)objectInfo.CreateInstance(reader);
                }

                HasValue = true;

                if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    throw new MicroLiteException(ExceptionMessages.Include_SingleRecordExpected);
                }

                _callback?.Invoke(this);
            }
        }
Exemple #10
0
        /// <summary>
        /// Creates an SqlQuery to perform an update based upon the values in the object delta.
        /// </summary>
        /// <param name="objectDelta">The object delta to create the query for.</param>
        /// <returns>
        /// The created <see cref="SqlQuery" />.
        /// </returns>
        public SqlQuery BuildUpdateSqlQuery(ObjectDelta objectDelta)
        {
            if (objectDelta == null)
            {
                throw new ArgumentNullException("objectDelta");
            }

            if (log.IsDebug)
            {
                log.Debug(LogMessages.SqlDialect_CreatingSqlQuery, "UPDATE");
            }

            var objectInfo = ObjectInfo.For(objectDelta.ForType);

            var builder = new UpdateSqlBuilder(this.SqlCharacters)
                          .Table(objectInfo);

            foreach (var change in objectDelta.Changes)
            {
                builder.SetColumnValue(change.Key, change.Value);
            }

            var sqlQuery = builder
                           .Where(objectInfo.TableInfo.IdentifierColumn.ColumnName).IsEqualTo(objectDelta.Identifier)
                           .ToSqlQuery();

            return(sqlQuery);
        }
Exemple #11
0
        internal override void BuildValue(IDataReader reader)
        {
            if (TypeConverter.IsNotEntityAndConvertible(resultType))
            {
                var typeConverter = TypeConverter.For(resultType) ?? TypeConverter.Default;

                while (reader.Read())
                {
                    var value = (T)typeConverter.ConvertFromDbValue(reader, 0, resultType);

                    this.values.Add(value);
                }
            }
            else
            {
                var objectInfo = ObjectInfo.For(resultType);

                while (reader.Read())
                {
                    var instance = (T)objectInfo.CreateInstance(reader);

                    this.values.Add(instance);
                }
            }

            this.HasValue = this.values.Count > 0;

            if (this.callback != null)
            {
                this.callback(this);
            }
        }
Exemple #12
0
        public void Insert(object instance)
        {
            this.ThrowIfDisposed();

            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            for (int i = 0; i < this.sessionListeners.InsertListeners.Count; i++)
            {
                this.sessionListeners.InsertListeners[i].BeforeInsert(instance);
            }

            var objectInfo = ObjectInfo.For(instance.GetType());

            objectInfo.VerifyInstanceForInsert(instance);

            object identifier = this.InsertReturningIdentifier(objectInfo, instance);

            for (int i = this.sessionListeners.InsertListeners.Count - 1; i >= 0; i--)
            {
                this.sessionListeners.InsertListeners[i].AfterInsert(instance, identifier);
            }
        }
        public void SetIdentifierValue_ThrowsNullReferenceException_IfIdentifierIsNull()
        {
            var objectInfo = ObjectInfo.For(typeof(Customer));

            Assert.Throws <NullReferenceException>(
                () => objectInfo.SetIdentifierValue(new Customer(), null));
        }
        public void For_ThrowsArgumentNullExceptonForNullForType()
        {
            var exception = Assert.Throws <ArgumentNullException>(
                () => ObjectInfo.For(null));

            Assert.Equal("forType", exception.ParamName);
        }
Exemple #15
0
        internal override async Task BuildValueAsync(DbDataReader reader, CancellationToken cancellationToken)
        {
            if (TypeConverter.IsNotEntityAndConvertible(s_resultType))
            {
                ITypeConverter typeConverter = TypeConverter.For(s_resultType) ?? TypeConverter.Default;

                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    var value = (T)typeConverter.ConvertFromDbValue(reader, 0, s_resultType);

                    Values.Add(value);
                }
            }
            else
            {
                IObjectInfo objectInfo = ObjectInfo.For(s_resultType);

                while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
                {
                    var instance = (T)objectInfo.CreateInstance(reader);

                    Values.Add(instance);
                }
            }

            HasValue = Values.Count > 0;

            _callback?.Invoke(this);
        }
        public void GetColumnInfo_ReturnsColumnInfo_IfColumnMapped()
        {
            var objectInfo = ObjectInfo.For(typeof(Customer));
            var columnInfo = objectInfo.GetColumnInfo("Name");

            Assert.NotNull(columnInfo);
            Assert.Equal("Name", columnInfo.ColumnName);
        }
        public void IsDefaultIdentifier_WhenIdentifierIsString()
        {
            var objectInfo = ObjectInfo.For(typeof(CustomerWithStringIdentifier));

            Assert.True(objectInfo.IsDefaultIdentifier(null));

            Assert.False(objectInfo.IsDefaultIdentifier("AFIK"));
        }
        public void IsDefaultIdentifier_WhenIdentifierIsInteger()
        {
            var objectInfo = ObjectInfo.For(typeof(Customer));

            Assert.True(objectInfo.IsDefaultIdentifier(0));

            Assert.False(objectInfo.IsDefaultIdentifier(18734));
        }
        public void IsDefaultIdentifier_WhenIdentifierIsGuid()
        {
            var objectInfo = ObjectInfo.For(typeof(CustomerWithGuidIdentifier));

            Assert.True(objectInfo.IsDefaultIdentifier(Guid.Empty));

            Assert.False(objectInfo.IsDefaultIdentifier(Guid.NewGuid()));
        }
        public void ForType_ReturnsTypePassedToConstructor()
        {
            var forType = typeof(Customer);

            var objectInfo = ObjectInfo.For(forType);

            Assert.Equal(forType, objectInfo.ForType);
        }
        public void For_ReturnsPocoObjectInfo_ForPocoType()
        {
            var forType = typeof(Customer);

            var objectInfo1 = ObjectInfo.For(forType);

            Assert.IsType <PocoObjectInfo>(objectInfo1);
        }
Exemple #22
0
        public void BuildSelectInsertIdSqlQuery()
        {
            var sqlDialect = new MySqlDialect();

            var sqlQuery = sqlDialect.BuildSelectInsertIdSqlQuery(ObjectInfo.For(typeof(Customer)));

            Assert.Equal("SELECT LAST_INSERT_ID()", sqlQuery.CommandText);
            Assert.Equal(0, sqlQuery.Arguments.Count);
        }
        public void SetIdentifierValue_ThrowsArgumentNullException_IfInstanceIsNull()
        {
            var objectInfo = ObjectInfo.For(typeof(Customer));

            var exception = Assert.Throws <ArgumentNullException>(
                () => objectInfo.SetIdentifierValue(null, 122323));

            Assert.Equal("instance", exception.ParamName);
        }
        public void CreateInstanceThrowsArgumentNullExceptionForNullReader()
        {
            var objectInfo = ObjectInfo.For(typeof(Customer));

            var exception = Assert.Throws <ArgumentNullException>(
                () => objectInfo.CreateInstance(null));

            Assert.Equal("reader", exception.ParamName);
        }
        public void For_ReturnsSameObjectInfo_ForSameType()
        {
            var forType = typeof(Customer);

            var objectInfo1 = ObjectInfo.For(forType);
            var objectInfo2 = ObjectInfo.For(forType);

            Assert.Same(objectInfo1, objectInfo2);
        }
        public void For_ThrowsMicroLiteException_IfNotClass()
        {
            var exception = Assert.Throws <MappingException>(
                () => ObjectInfo.For(typeof(CustomerStruct)));

            Assert.Equal(
                ExceptionMessages.ObjectInfo_TypeMustBeClass.FormatWith(typeof(CustomerStruct).Name),
                exception.Message);
        }
        public void For_ThrowsMappingException_IfNonPublicClass()
        {
            var exception = Assert.Throws <MappingException>(
                () => ObjectInfo.For(typeof(InternalCustomer)));

            Assert.Equal(
                ExceptionMessages.ObjectInfo_TypeMustBePublic.FormatWith(typeof(InternalCustomer).Name),
                exception.Message);
        }
        public void For_ThrowsMappingException_IfNoDefaultConstructor()
        {
            var exception = Assert.Throws <MappingException>(
                () => ObjectInfo.For(typeof(CustomerWithNoDefaultConstructor)));

            Assert.Equal(
                ExceptionMessages.ObjectInfo_TypeMustHaveDefaultConstructor.FormatWith(typeof(CustomerWithNoDefaultConstructor).Name),
                exception.Message);
        }
        public void For_ThrowsMappingException_IfAbstractClass()
        {
            var exception = Assert.Throws <MappingException>(
                () => ObjectInfo.For(typeof(AbstractCustomer)));

            Assert.Equal(
                ExceptionMessages.ObjectInfo_TypeMustNotBeAbstract.FormatWith(typeof(AbstractCustomer).Name),
                exception.Message);
        }
        public void BuildSelectInsertIdSqlQuery()
        {
            var sqlDialect = new FirebirdSqlDialect();

            var sqlQuery = sqlDialect.BuildSelectInsertIdSqlQuery(ObjectInfo.For(typeof(Customer)));

            Assert.Equal(string.Empty, sqlQuery.CommandText);
            Assert.Equal(0, sqlQuery.Arguments.Count);
        }