コード例 #1
0
ファイル: DbAccessLayer.cs プロジェクト: radtek/DataAccess
        internal async Task <IEnumerable <object> > EnumerateDataRecordsAsync(IDbCommand query,
                                                                              bool egarLoading,
                                                                              DbClassInfoCache type,
                                                                              CommandBehavior executionHint = CommandBehavior.Default)
        {
            var resultList = new List <object>();

            if (!egarLoading)
            {
                await EnumerateAsync(query,
                                     record =>
                {
                    resultList.Add(SetPropertysViaReflection(type, EagarDataRecord.WithExcludedFields(record)));
                },
                                     executionHint);
            }
            else
            {
                var recordCache = new List <EagarDataRecord>();
                await EnumerateAsync(query,
                                     record => { recordCache.Add(EagarDataRecord.WithExcludedFields(record)); }, executionHint);

                resultList.AddRange(recordCache
                                    .Select(f => SetPropertysViaReflection(type, f))
                                    .ToArray());
            }

            return(resultList);
        }
コード例 #2
0
        /// <summary>
        ///     Creates a new Instance based on possible Ctor's and the given
        ///     <paramref name="reader" />
        /// </summary>
        /// <returns></returns>
        public static object SetPropertiesViaReflection(
            this DbClassInfoCache type,
            EagarDataRecord reader,
            DbAccessType?accessType = null,
            DbConfig config         = null)
        {
            if (reader == null)
            {
                return(null);
            }

            bool created;
            var  source = DbAccessLayer.CreateInstance(type, reader, out created);

            if (created)
            {
                return(source);
            }

            if (config == null)
            {
                config = new DbConfig(true);
            }

#pragma warning disable 618
            return(DbAccessLayer.ReflectionPropertySet(config, source, type, reader, new DbAccessLayer.ReflectionSetCacheModel(), accessType));

#pragma warning restore 618
        }
コード例 #3
0
                public void ReadXml(XmlReader reader)
                {
                    var listOfListOfRecords = new List <List <EagarDataRecord> >();

                    if (!reader.IsEmptyElement)
                    {
                        reader.ReadStartElement();                        //<lrec>
                        while (reader.Name == "lrec")
                        {
                            var listOfRecords = new List <EagarDataRecord>();
                            if (!reader.IsEmptyElement)
                            {
                                reader.ReadStartElement();                                //<rec>
                                while (reader.Name == "rec")
                                {
                                    var record = new EagarDataRecord();
                                    record.ReadXml(reader);
                                    listOfRecords.Add(record);
                                    reader.ReadEndElement();                            //<rec>
                                }
                                reader.ReadEndElement();                                //</lrec>
                            }
                            else
                            {
                                reader.ReadStartElement();                                //<lrec>
                            }
                            listOfListOfRecords.Add(listOfRecords);
                        }
                    }

                    Data = listOfListOfRecords;
                }
コード例 #4
0
 public static NonObservableDbCollection <T> FromXml(string xml)
 {
     return(new NonObservableDbCollection <T>(
                XmlDataRecord.TryParse(xml,
                                       typeof(T), false)
                .CreateListOfItems()
                .Select(item => typeof(T)
                        .GetClassInfo()
                        .SetPropertysViaReflection(EagarDataRecord.WithExcludedFields(item)))));
 }
コード例 #5
0
        public static AppRole Factory(EagarDataRecord reader)
        {
            var super = new AppRole();

            super.AppRoleId    = (int)reader["AppRoleId"];
            super.RoleName     = (string)reader["RoleName"];
            super.NormRoleName = (string)reader["NormRoleName"];
            var readersOfAppUser = ((EagarDataRecord[])reader["AppUser"]);

            super.AppUser = readersOfAppUser == null ? null : new DbCollection <AppUser>(readersOfAppUser.Select(item => ((AppUser)(typeof(AppUser).GetClassInfo().SetPropertiesViaReflection(reader: item)))));
            return(super);
        }
コード例 #6
0
ファイル: DbAccessLayer.cs プロジェクト: radtek/DataAccess
        internal List <List <EagarDataRecord> > EnumerateMarsDataRecords(
            IDbCommand query)
        {
            Database.PrepaireRemoteExecution(query);
            try
            {
                if (ThreadSave)
                {
                    Monitor.Enter(_lockRoot);
                }

                return(Database.Run(
                           s =>
                {
                    var records = new List <List <EagarDataRecord> >();
                    using (query)
                    {
                        query.Connection = query.Connection ?? s.GetConnection();
                        query.Transaction = query.Transaction ?? s.ConnectionController.Transaction;
                        using (var dr = query.ExecuteReader())
                        {
                            try
                            {
                                do
                                {
                                    var resultSet = new List <EagarDataRecord>();
                                    while (dr.Read())
                                    {
                                        resultSet.Add(EagarDataRecord.WithExcludedFields(dr));
                                    }

                                    records.Add(resultSet);
                                } while (dr.NextResult());
                            }
                            catch (Exception ex)
                            {
                                RaiseFailedQuery(this, query, ex);
                                throw;
                            }
                        }
                    }

                    return records;
                }));
            }
            finally
            {
                if (ThreadSave)
                {
                    Monitor.Exit(_lockRoot);
                }
            }
        }
コード例 #7
0
        public static Users Factory(EagarDataRecord reader)
        {
            var super = new Users();

            super.UserId    = (int)reader["UserId"];
            super.Username  = (string)reader["Username"];
            super.IdAccount = (Nullable <Int32>)reader["IdAccount"];
            var readersOfAppUser = ((EagarDataRecord[])reader["AppUser"])?.FirstOrDefault();

            super.AppUser = readersOfAppUser == null ? null : ((AppUser)(typeof(AppUser).GetClassInfo().SetPropertiesViaReflection(reader: readersOfAppUser)));
            var readersOfPlayback = ((EagarDataRecord[])reader["Playback"]);

            super.Playback = readersOfPlayback == null ? null : new DbCollection <Playback>(readersOfPlayback.Select(item => ((Playback)(typeof(Playback).GetClassInfo().SetPropertiesViaReflection(reader: item)))));
            return(super);
        }
コード例 #8
0
        public static Genre Factory(EagarDataRecord reader)
        {
            var super = new Genre();

            super.GenreId        = (int)reader["GenreId"];
            super.Name           = (string)reader["Name"];
            super.Location       = (string)reader["Location"];
            super.PlaybackLength = (Nullable <Int32>)reader["PlaybackLength"];
            super.OffsetStart    = (Nullable <Int32>)reader["OffsetStart"];
            super.OffsetEnd      = (Nullable <Int32>)reader["OffsetEnd"];
            var readersOfSeason = ((EagarDataRecord[])reader["Season"]);

            super.Season = readersOfSeason == null ? null : new DbCollection <Season>(readersOfSeason.Select(item => ((Season)(typeof(Season).GetClassInfo().SetPropertiesViaReflection(reader: item)))));
            return(super);
        }
コード例 #9
0
        public static Playback Factory(EagarDataRecord reader)
        {
            var super = new Playback();

            super.PlaybackId = (int)reader["PlaybackId"];
            super.IdTitle    = (int)reader["IdTitle"];
            super.IdUser     = (int)reader["IdUser"];
            super.Position   = (int)reader["Position"];
            var readersOfTitle = ((EagarDataRecord[])reader["Title"])?.FirstOrDefault();

            super.Title = readersOfTitle == null ? null : ((Title)(typeof(Title).GetClassInfo().SetPropertiesViaReflection(reader: readersOfTitle)));
            var readersOfUsers = ((EagarDataRecord[])reader["Users"])?.FirstOrDefault();

            super.Users = readersOfUsers == null ? null : ((Users)(typeof(Users).GetClassInfo().SetPropertiesViaReflection(reader: readersOfUsers)));
            return(super);
        }
コード例 #10
0
        public static AppUser Factory(EagarDataRecord reader)
        {
            var super = new AppUser();

            super.AppUserId    = (int)reader["AppUserId"];
            super.Username     = (string)reader["Username"];
            super.NormUsername = (string)reader["NormUsername"];
            super.Password     = (string)reader["Password"];
            super.IdRole       = (int)reader["IdRole"];
            var readersOfAppRole = ((EagarDataRecord[])reader["AppRole"])?.FirstOrDefault();

            super.AppRole = readersOfAppRole == null ? null : ((AppRole)(typeof(AppRole).GetClassInfo().SetPropertiesViaReflection(reader: readersOfAppRole)));
            var readersOfUsers = ((EagarDataRecord[])reader["Users"]);

            super.Users = readersOfUsers == null ? null : new DbCollection <Users>(readersOfUsers.Select(item => ((Users)(typeof(Users).GetClassInfo().SetPropertiesViaReflection(reader: item)))));
            return(super);
        }
コード例 #11
0
        private static void SetRelationOnRecord(string virtualColumnName,
                                                EagarDataRecord[] relationRecordSource,
                                                int targetOrdinal,
                                                EagarDataRecord naturalReader,
                                                int sourceOrdinal)
        {
            naturalReader.Add(virtualColumnName, relationRecordSource.Where(join =>
            {
                var left  = naturalReader[targetOrdinal];
                var right = @join[sourceOrdinal];
                if (left == null && right == null)
                {
                    return(false);
                }

                return(left == right || (left != null && right != null && left.Equals(right)));
            }).ToArray());
        }
コード例 #12
0
        public static Title Factory(EagarDataRecord reader)
        {
            var super = new Title();

            super.TitleId        = (int)reader["TitleId"];
            super.Name           = (string)reader["Name"];
            super.Location       = (string)reader["Location"];
            super.OrderNo        = (Nullable <Int32>)reader["OrderNo"];
            super.PlaybackLength = (Nullable <Int32>)reader["PlaybackLength"];
            super.OffsetStart    = (Nullable <Int32>)reader["OffsetStart"];
            super.OffsetEnd      = (Nullable <Int32>)reader["OffsetEnd"];
            super.IdSeason       = (int)reader["IdSeason"];
            var readersOfSeason = ((EagarDataRecord[])reader["Season"])?.FirstOrDefault();

            super.Season = readersOfSeason == null ? null : ((Season)(typeof(Season).GetClassInfo().SetPropertiesViaReflection(reader: readersOfSeason)));
            var readersOfPlayback = ((EagarDataRecord[])reader["Playback"]);

            super.Playback = readersOfPlayback == null ? null : new DbCollection <Playback>(readersOfPlayback.Select(item => ((Playback)(typeof(Playback).GetClassInfo().SetPropertiesViaReflection(reader: item)))));
            return(super);
        }
コード例 #13
0
        public static Season Factory(EagarDataRecord reader)
        {
            var super = new Season();

            super.SeasonId       = (int)reader["SeasonId"];
            super.Name           = (string)reader["Name"];
            super.Location       = (string)reader["Location"];
            super.PlaybackLength = (Nullable <Int32>)reader["PlaybackLength"];
            super.OffsetStart    = (Nullable <Int32>)reader["OffsetStart"];
            super.OffsetEnd      = (Nullable <Int32>)reader["OffsetEnd"];
            super.OrderNo        = (int)reader["OrderNo"];
            super.IdGenre        = (int)reader["IdGenre"];
            var readersOfGenre = ((EagarDataRecord[])reader["Genre"])?.FirstOrDefault();

            super.Genre = readersOfGenre == null ? null : ((Genre)(typeof(Genre).GetClassInfo().SetPropertiesViaReflection(reader: readersOfGenre)));
            var readersOfTitle = ((EagarDataRecord[])reader["Title"]);

            super.Title = readersOfTitle == null ? null : new DbCollection <Title>(readersOfTitle.Select(item => ((Title)(typeof(Title).GetClassInfo().SetPropertiesViaReflection(reader: item)))));
            return(super);
        }
コード例 #14
0
        public EagarDataRecord[][] ExecuteMARSCommand(DbAccessLayer db, IDbCommand query, out int recordsAffected)
        {
            var recordsAffectedA = 0;
            var result           = db.Database.Run(
                s =>
            {
                var records = new List <EagarDataRecord[]>();
                using (query)
                {
                    query.Connection  = query.Connection ?? s.GetConnection();
                    query.Transaction = query.Transaction ?? s.ConnectionController.Transaction;
                    using (var dr = query.ExecuteReader())
                    {
                        recordsAffectedA = dr.RecordsAffected;
                        try
                        {
                            do
                            {
                                var resultSet = new List <EagarDataRecord>();
                                while (dr.Read())
                                {
                                    resultSet.Add(EagarDataRecord.WithExcludedFields(dr));
                                }

                                records.Add(resultSet.ToArray());
                            } while (dr.NextResult());
                        }
                        catch (Exception ex)
                        {
                            db.RaiseFailedQuery(this, query, ex);
                            throw;
                        }
                    }
                }

                return(records.ToArray());
            });

            recordsAffected = recordsAffectedA;
            return(result);
        }
コード例 #15
0
        /// <summary>
        ///     Creates a new Instance based on possible Ctor's and the given
        ///     <paramref name="reader" />
        /// </summary>
        /// <returns></returns>
        public static object SetPropertiesViaReflection(
            this DbClassInfoCache type,
            XmlDataRecord reader,
            DbAccessType?accessType = null,
            DbConfig config         = null)
        {
            if (reader == null)
            {
                return(null);
            }

            var eagerReader = new EagarDataRecord();

            for (int i = 0; i < reader.FieldCount; i++)
            {
                eagerReader.Add(eagerReader.GetName(i), eagerReader[i]);
            }

            bool created;
            var  source = DbAccessLayer.CreateInstance(type, eagerReader, out created);

            if (created)
            {
                return(source);
            }

            if (config == null)
            {
                config = new DbConfig(true);
            }

#pragma warning disable 618
            return(DbAccessLayer.ReflectionPropertySet(config, source, type, eagerReader, new DbAccessLayer.ReflectionSetCacheModel(), accessType));

#pragma warning restore 618
        }
コード例 #16
0
 public virtual EagarDataRecord Transform(EagarDataRecord reader, Type entityType, QueryProcessingRecordsContext context)
 {
     return(reader);
 }
コード例 #17
0
 /// <summary>
 ///     Creates a new Instance based on possible Ctor's and the given
 ///     <paramref name="reader" />
 /// </summary>
 /// <returns></returns>
 public object SetPropertysViaReflection(DbClassInfoCache type, EagarDataRecord reader, DbAccessType?accessType)
 {
     return(type.SetPropertiesViaReflection(reader, DbAccessType, Config));
 }
コード例 #18
0
        private void CreateJoinMapping(
            JoinParseInfo joinTableQueryPart,
            EagarDataRecord[] readers,
            Type entityType,
            QueryProcessingRecordsContext context)
        {
            var parentedReaders = new List <EagarDataRecord>();
            var property        = joinTableQueryPart.TargetProperty;

            var sourceColumn = joinTableQueryPart.TargetColumnName;
            var targetColumn = joinTableQueryPart.SourceColumnName;

            if (sourceColumn == null)
            {
                throw new InvalidOperationException();
            }
            if (targetColumn == null)
            {
                throw new InvalidOperationException();
            }

            var fields        = joinTableQueryPart.Columns.ToArray();
            var fieldsOfChild = fields
                                .Select((item, index) => item.ColumnIdentifier())
                                .ToArray();

            var columnMapping             = new Dictionary <string, int>();
            var sourceColumnsIndexMapping = context.Columns.ToArray().Select((item, index) => new
            {
                item,
                index
            }).ToDictionary(e => e.item, e => e.index);

            foreach (var fieldOfChild in fieldsOfChild)
            {
                var child         = fieldOfChild;
                var indexOfSource =
                    sourceColumnsIndexMapping
                    .FirstOrDefault(e => e.Key.ColumnIdentifier().Equals(child));
                if (columnMapping.ContainsKey(indexOfSource.Key.NaturalName))
                {
                    throw new InvalidOperationException($"Column name collision detected. Column '{indexOfSource.Key.NaturalName}'")
                          {
                              Data =
                              {
                                  { "Columns", sourceColumnsIndexMapping },
                                  { "Field",   indexOfSource             },
                              }
                          };
                }

                columnMapping.Add(indexOfSource.Key.NaturalName, indexOfSource.Value);
            }

            var groupBy = columnMapping[columnMapping.FirstOrDefault().Key];
            //TODO might not be the PrimaryKey of the foreign table

            var readerGroups = readers
                               .GroupBy(e => e[groupBy])
                               .Select(e => e.First())
                               .ToArray();

            foreach (var readerGroup in readerGroups)
            {
                var naturalReader = new EagarDataRecord(columnMapping.Keys.ToArray(),
                                                        new ArrayList(columnMapping.Values.Select(f => readerGroup[f]).ToArray()));

                parentedReaders.Add(naturalReader);
            }

            Mappings.Add(new RelationMapping()
            {
                TargetColumns = joinTableQueryPart.Columns,
                SourceColumns = context.Columns
                                .Where(e => e.Alias.Equals(joinTableQueryPart.SourceTable))
                                .ToArray(),
                Records      = parentedReaders.ToArray(),
                SourceColumn = sourceColumn,
                TargetColumn = targetColumn,
                TargetName   = property.PropertyName,
                TargetType   = entityType,
                SourceAlias  = joinTableQueryPart.Alias,
                TargetAlias  = joinTableQueryPart.SourceTable
            });

            if (readerGroups.Any())
            {
                foreach (var subJoinTableQueryPart in joinTableQueryPart.DependingJoins)
                {
                    CreateJoinMapping(subJoinTableQueryPart,
                                      readers,
                                      subJoinTableQueryPart.TargetTableType,
                                      context);
                }
            }

            foreach (var eagarDataRecord in readers)
            {
                foreach (var columnInfo in joinTableQueryPart.Columns)
                {
                    //eagarDataRecord.Remove(columnInfo.ColumnIdentifier());
                    eagarDataRecord.Remove(columnInfo.ColumnIdentifier().TrimAlias());
                }
            }

            context.Columns = context.Columns
                              .Except(joinTableQueryPart.Columns)
                              .ToArray();
        }
コード例 #19
0
ファイル: DbAccessLayer.cs プロジェクト: radtek/DataAccess
        public static object ReflectionPropertySet(
            DbConfig config,
            object instance,
            DbClassInfoCache info,
            EagarDataRecord reader,
            ReflectionSetCacheModel cacheModel,
            DbAccessType?dbAccessType)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            if (reader == null)
            {
                return(instance);
            }

            //Left c# property name and right the object to read from the reader
            //var listofpropertys = new Dictionary<string, object>();

            var propertys = info.Propertys.ToArray();
            var instanceOfFallbackList = new Dictionary <string, object>();
            IDictionary <int, DbPropertyInfoCache> cache = new Dictionary <int, DbPropertyInfoCache>();

            for (var i = 0; i < reader.FieldCount; i++)
            {
                info.Propertys.TryGetValue(info.SchemaMappingDatabaseToLocal(reader.GetName(i)), out var val);
                cache.Add(i, val);
            }

            //var containsKey = cacheModel?.Cache.ContainsKey(info.Type);
            //if (containsKey != true)
            //{
            //	for (var i = 0; i < reader.FieldCount; i++)
            //	{
            //		info.Propertys.TryGetValue(info.SchemaMappingDatabaseToLocal(reader.GetName(i)), out var val);
            //		cache.Add(i, val);
            //	}

            //	if (containsKey == false)
            //	{
            //		cacheModel.Cache[info.Type] = cache;
            //	}
            //}
            //if (containsKey == true)
            //{
            //	cache = cacheModel.Cache[info.Type];
            //}

            for (var i = 0; i < reader.FieldCount; i++)
            {
                var property = cache[i];
                var value    = reader.GetValue(i);

                if (property != null)
                {
                    var attributes = property.Attributes;
                    var valueConverterAttributeModel =
                        attributes.FirstOrDefault(s => s.Attribute is ValueConverterAttribute);

                    //Should the SQL value be converted
                    if (valueConverterAttributeModel != null)
                    {
                        var converter = valueConverterAttributeModel.Attribute as ValueConverterAttribute;
                        //Create the converter and then convert the value before everything else
                        var valueConverter = converter.CreateConverter();
                        value = valueConverter.Convert(value, property.PropertyInfo.PropertyType, converter.Parameter,
                                                       CultureInfo.CurrentCulture);
                    }

                    var xmlAttributeModel =
                        attributes.FirstOrDefault(s => s.Attribute is FromXmlAttribute);

                    //should the Content be considerd as XML text?
                    if (xmlAttributeModel != null)
                    {
                        //Get the XML text and check if its null or empty
                        var xmlStream = value.ToString();
                        if (string.IsNullOrEmpty(xmlStream))
                        {
                            continue;
                        }

                        //Check for List
                        //if this is a list we are expecting other entrys inside
                        if (property.CheckForListInterface())
                        {
                            //target Property is of type list
                            //so expect a xml valid list Take the first element and expect the propertys inside this first element
                            var record = XmlDataRecord.TryParse(xmlStream,
                                                                property.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault(), false,
                                                                config);
                            var xmlDataRecords = record.CreateListOfItems();

                            var genericArguments =
                                config.GetOrCreateClassInfoCache(
                                    property.PropertyInfo.PropertyType.GetGenericArguments().FirstOrDefault());
                            var enumerableOfItems =
                                xmlDataRecords.Select(
                                    s => genericArguments
                                    .SetPropertysViaReflection(EagarDataRecord.WithExcludedFields(s),
                                                               dbAccessType, config)).ToList();
                            object castedList;

                            if (genericArguments.Type.IsClass &&
                                genericArguments.Type.GetInterface("INotifyPropertyChanged") != null)
                            {
                                var caster =
                                    typeof(DbCollection <>).MakeGenericType(genericArguments.Type)
                                    .GetConstructor(new[] { typeof(IEnumerable) });
                                castedList = caster.Invoke(new object[] { enumerableOfItems });
                            }
                            else
                            {
                                var caster =
                                    typeof(NonObservableDbCollection <>).MakeGenericType(genericArguments.Type)
                                    .GetConstructor(new[] { typeof(IEnumerable) });
                                castedList = caster.Invoke(new object[] { enumerableOfItems });
                            }

                            property.Setter.Invoke(instance, castedList);
                        }
                        else
                        {
                            var classInfo = config.GetOrCreateClassInfoCache(property
                                                                             .PropertyInfo
                                                                             .PropertyType);

                            var xmlDataRecord = XmlDataRecord.TryParse(xmlStream, property.PropertyInfo.PropertyType,
                                                                       true, config);

                            //the t
                            var xmlSerilizedProperty = classInfo.SetPropertysViaReflection(
                                EagarDataRecord.WithExcludedFields(xmlDataRecord), dbAccessType,
                                config);
                            property.Setter.Invoke(instance, xmlSerilizedProperty);
                        }
                    }
                    else if (value is DBNull || value == null)
                    {
                        //property.Setter.Invoke(instance, new object[] {null});
                    }
                    else if (value is IEnumerable <EagarDataRecord> navigationValue)
                    {
                        Type targetType;
                        if (property.CheckForListInterface())
                        {
                            targetType = property.PropertyType.GetElementType();
                            if (targetType == null)
                            {
                                targetType = property.PropertyType.GetGenericArguments().FirstOrDefault();
                            }
                        }
                        else
                        {
                            targetType = property.PropertyType;
                        }

                        var classInfo   = config.GetOrCreateClassInfoCache(targetType);
                        var enumeration = navigationValue.Select(subReader =>
                        {
                            bool created;
                            var source = CreateInstance(classInfo, subReader, out created);
                            if (created)
                            {
                                return(source);
                            }
                            return(ReflectionPropertySet(config, source, classInfo, subReader, cacheModel, dbAccessType));
                        }).ToArray();

                        if (property.CheckForListInterface())
                        {
                            var caster =
                                typeof(DbCollection <>).MakeGenericType(targetType)
                                .GetConstructor(new[] { typeof(IEnumerable) });
                            var castedList = caster.Invoke(new object[] { enumeration });
                            property.Setter.Invoke(instance, castedList);
                        }
                        else
                        {
                            property.Setter.Invoke(instance, enumeration.FirstOrDefault());
                        }
                    }
                    else
                    {
                        object changedType = value;
                        if (property.PropertyType.IsInstanceOfType(value))
                        {
                            changedType = value;
                        }
                        else
                        {
                            if (!DataConverterExtensions.ChangeType(ref changedType, property.PropertyInfo.PropertyType))
                            {
                                continue;
                            }
                        }

                        //if (value.GetType() != property.PropertyInfo.PropertyType)
                        //{
                        //	changedType = DataConverterExtensions.ChangeType(value, property.PropertyInfo.PropertyType);
                        //}
                        //else
                        //{
                        //	changedType = value;
                        //}

                        property.Setter.Invoke(instance, changedType);
                    }
                }
                //This variable is null if we tried to find a property with the LoadNotImplimentedDynamicAttribute but did not found it
                else if (instanceOfFallbackList != null)
                {
                    //no property found Look for LoadNotImplimentedDynamicAttribute property to include it

                    if (instanceOfFallbackList.Any())
                    {
                        instanceOfFallbackList.Add(reader.GetName(i), value);
                    }
                    else
                    {
                        var maybeFallbackProperty =
                            propertys.FirstOrDefault(
                                s => s.Value.Attributes.Any(e => e.Attribute is LoadNotImplimentedDynamicAttribute));
                        if (maybeFallbackProperty.Value != null)
                        {
                            instanceOfFallbackList =
                                (Dictionary <string, object>)maybeFallbackProperty.Value.Getter.Invoke(instance);
                            if (instanceOfFallbackList == null)
                            {
                                instanceOfFallbackList = new Dictionary <string, object>();
                                maybeFallbackProperty.Value.Setter.Invoke(instance, instanceOfFallbackList);
                            }

                            instanceOfFallbackList.Add(reader.GetName(i), value);
                        }
                        else
                        {
                            instanceOfFallbackList = null;
                        }
                    }
                }
            }

            //foreach (var item in listofpropertys)
            //{
            //	var property = propertys.FirstOrDefault(s => s.PropertyName == item.Key);

            //}
            return(instance);
        }
コード例 #20
0
ファイル: DbAccessLayer.cs プロジェクト: radtek/DataAccess
//		/// <summary>
//		///     Creates a new Instance based on possible Ctor's and the given
//		///     <paramref name="reader" />
//		/// </summary>
//		/// <returns></returns>
//		public object SetPropertysViaReflection(DbClassInfoCache type, EagarDataRecord reader,
//			Dictionary<int, DbPropertyInfoCache> mapping)
//		{
//			bool created;
//			var source = CreateInstance(type, reader, out created);
//			if (created)
//			{
//				return source;
//			}

//#pragma warning disable 618
//			return ReflectionPropertySet(Config, source, type, reader, mapping, DbAccessType);
//#pragma warning restore 618
//		}

//		/// <summary>
//		///     Creates an instance based on a Ctor injection or Reflection loading
//		///     or when using a MsCoreLib type direct enumeration
//		/// </summary>
//		/// <returns></returns>
//		public static object CreateInstance(DbClassInfoCache classInfo,
//			EagarDataRecord reader)
//		{
//			bool loaded;
//			return CreateInstance(classInfo, reader, out loaded);
//		}

        /// <summary>
        ///     Creates an instance based on a Ctor injection or Reflection loading
        ///     or when using a MsCoreLib type direct enumeration
        /// </summary>
        /// <returns></returns>
        public static object CreateInstance(DbClassInfoCache classInfo,
                                            EagarDataRecord reader,
                                            out bool fullLoaded,
                                            DbAccessType?accessType = null)
        {
            reader.WrapNulls = true;

            if (classInfo.IsMsCoreFrameworkType && reader.FieldCount == 1)
            {
                fullLoaded = true;
                var plainValue = reader.GetValue(0);

                return(plainValue);
            }

            if (classInfo.Factory != null)
            {
                fullLoaded = classInfo.FullFactory;
                var fullObject = classInfo.Factory(reader);
                return(fullObject);
            }

            var factories = classInfo.Constructors.Where(s =>
                                                         s.Arguments.Count == 1 &&
                                                         s.Arguments.First().Type.IsAssignableFrom(typeof(EagarDataRecord)))
                            .ToArray();

            var constructor = factories.FirstOrDefault(s =>
                                                       s.Attributes.Any(f =>
                                                                        f.Attribute is ObjectFactoryMethodAttribute attribute
                                                                        &&
                                                                        (!accessType.HasValue ||
                                                                         attribute.TargetDatabase ==
                                                                         accessType.Value))) ??
                              factories.FirstOrDefault();

            //maybe single ctor with param

            if (constructor != null)
            {
                if (constructor.Arguments.Count == 1 &&
                    constructor.Arguments.First().Type.IsAssignableFrom(typeof(EagarDataRecord)))
                {
                    classInfo.FullFactory = true;
                    classInfo.Factory     = s => constructor.Invoke(new object[] { s });
                    return(CreateInstance(classInfo, reader, out fullLoaded, accessType));
                }
            }
            else
            {
                //check for a Factory method
                var factory =
                    classInfo.Mehtods
                    .FirstOrDefault(s => s.Attributes.Any(f => f.Attribute is ObjectFactoryMethodAttribute));

                if (factory != null)
                {
                    if (factory.MethodInfo.IsStatic)
                    {
                        var methodInfo = factory.MethodInfo as MethodInfo;
                        if (methodInfo != null)
                        {
                            var returnType = methodInfo.ReturnParameter;

                            if (returnType != null && returnType.ParameterType == classInfo.Type)
                            {
                                if (factory.Arguments.Count == 1 &&
                                    factory.Arguments.First().Type.IsAssignableFrom(typeof(EagarDataRecord)))
                                {
                                    classInfo.FullFactory = true;
                                    classInfo.Factory     = s => factory.Invoke(new object[] { reader });
                                    return(CreateInstance(classInfo, reader, out fullLoaded, accessType));
                                }
                            }
                        }
                    }
                }
            }

            var emptyCtor = classInfo.Constructors.FirstOrDefault(f => !f.Arguments.Any());

            if (emptyCtor == null)
            {
                throw new NotSupportedException(
                          "You have to define ether an ObjectFactoryMethod as static or constructor with and IDataReader or an constructor without any arguments");
            }

            classInfo.FullFactory = false;
            classInfo.Factory     = s => emptyCtor.Invoke();
            return(CreateInstance(classInfo, reader, out fullLoaded, accessType));
        }
コード例 #21
0
ファイル: DbAccessLayer.cs プロジェクト: radtek/DataAccess
        ///// <summary>
        /////     Creates a Strong typed query that awaits a Result
        ///// </summary>
        ///// <returns></returns>
        //public RootQuery Query(Type targetType)
        //{
        //	return new RootQuery(this, targetType);
        //}

        ///// <summary>
        /////     Creates a Strong typed query that awaits a Result
        ///// </summary>
        ///// <returns></returns>
        //public RootQuery Query<T>()
        //{
        //	return new RootQuery(this, typeof(T));
        //}

        /// <summary>
        ///     Creates a new Instance based on possible Ctor's and the given
        ///     <paramref name="reader" />
        /// </summary>
        /// <returns></returns>
        public object SetPropertysViaReflection(DbClassInfoCache type, EagarDataRecord reader)
        {
            return(SetPropertysViaReflection(type, reader, DbAccessType));
        }