Ejemplo n.º 1
0
        public SqlTable(MappingSchema mappingSchema, Type objectType)
            : this(mappingSchema)
        {
            bool isSet;
            _database   = _mappingSchema.MetadataProvider.GetDatabaseName(objectType, _mappingSchema.Extensions, out isSet);
            _owner      = _mappingSchema.MetadataProvider.GetOwnerName(objectType, _mappingSchema.Extensions, out isSet);
            _name       = _mappingSchema.MetadataProvider.GetTableName(objectType, _mappingSchema.Extensions, out isSet);
            _objectType = objectType;

            var typeExt = TypeExtension.GetTypeExtension(objectType, _mappingSchema.Extensions);

            foreach (MemberMapper mm in MappingSchema.GetObjectMapper(objectType))
            {
                if (mm.MapMemberInfo.SqlIgnore == false)
                {
                    var ua =
                        _mappingSchema.MetadataProvider.GetNonUpdatableAttribute(objectType, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                    var order = _mappingSchema.MetadataProvider.GetPrimaryKeyOrder(objectType, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                    Fields.Add(new SqlField(
                                   mm.Type,
                                   mm.MemberName,
                                   mm.Name,
                                   mm.MapMemberInfo.Nullable,
                                   isSet ? order : int.MinValue,
                                   ua,
                                   mm));
                }
            }
        }
Ejemplo n.º 2
0
        protected SqlQueryInfo CreateUpdateSqlText(DbManager db, Type type)
        {
            TypeExtension        typeExt = TypeExtension.GetTypeExtension(type, Extensions);
            ObjectMapper         om      = db.MappingSchema.GetObjectMapper(type);
            StringBuilder        sb      = new StringBuilder();
            SqlQueryInfo         query   = new SqlQueryInfo(om);
            MetadataProviderBase mp      = MappingSchema.MetadataProvider;

            sb.AppendFormat("UPDATE\n\t{0}\nSET\n",
                            db.DataProvider.Convert(GetTableName(type), ConvertType.NameToQueryTable));

            foreach (MemberMapper mm in GetFieldList(om))
            {
                bool isSet;

                if (!mp.GetNonUpdatableFlag(type, typeExt, mm.MemberAccessor, out isSet) || !isSet)
                {
                    SqlQueryParameterInfo p = query.AddParameter(
                        db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryParameter).ToString(),
                        mm.Name);

                    sb.AppendFormat("\t{0} = {1},\n",
                                    db.DataProvider.Convert(p.FieldName, ConvertType.NameToQueryField),
                                    p.ParameterName);
                }
            }

            sb.Remove(sb.Length - 2, 1);

            AddWherePK(db, query, sb);

            query.QueryText = sb.ToString();

            return(query);
        }
Ejemplo n.º 3
0
        protected SqlQueryInfo CreateInsertSqlText(DbManager db, Type type, int nParameter)
        {
            TypeExtension        typeExt = TypeExtension.GetTypeExtension(type, Extensions);
            ObjectMapper         om      = db.MappingSchema.GetObjectMapper(type);
            List <MemberMapper>  list    = new List <MemberMapper>();
            StringBuilder        sb      = new StringBuilder();
            SqlQueryInfo         query   = new SqlQueryInfo(om);
            MetadataProviderBase mp      = MappingSchema.MetadataProvider;

            sb.Append("INSERT INTO ");
            AppendTableName(sb, db, type);
            sb.Append(" (\n");

            foreach (MemberMapper mm in GetFieldList(om))
            {
                // IT: This works incorrectly for complex mappers.
                //
                // [2009-03-24] ili: use mm.MemberAccessor instead of mm.ComplexMemberAccessor
                // as in CreateUpdateSqlText
                //

                bool isSet;

                if (mp.GetNonUpdatableAttribute(type, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet) == null || !isSet)
                {
                    sb.AppendFormat("\t{0},\n",
                                    db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryField));
                    list.Add(mm);
                }
            }

            sb.Remove(sb.Length - 2, 1);

            sb.Append(") VALUES (\n");

            foreach (MemberMapper mm in list)
            {
                SqlQueryParameterInfo p = query.AddParameter(
                    db.DataProvider.Convert(mm.Name + "_P", ConvertType.NameToQueryParameter).ToString(),
                    mm.Name);

                if (nParameter < 0)
                {
                    sb.AppendFormat("\t{0},\n", p.ParameterName);
                }
                //sb.AppendFormat("\t{0},\n", db.DataProvider.Convert(p.ParameterName, ConvertType.NameToQueryParameter));
                else
                {
                    sb.AppendFormat("\t{{{0}}},\n", nParameter++);
                }
            }

            sb.Remove(sb.Length - 2, 1);

            sb.Append(")");

            query.QueryText = sb.ToString();

            return(query);
        }
Ejemplo n.º 4
0
        protected virtual MemberMapper[] GetNonKeyFieldList(ObjectMapper om)
        {
            var typeExt = TypeExtension.GetTypeExtension(om.TypeAccessor.OriginalType, Extensions);
            var list    = new List <MemberMapper>();

            foreach (MemberMapper mm in om)
            {
                if (mm.MapMemberInfo.SqlIgnore)
                {
                    continue;
                }

                var ma = mm.MapMemberInfo.MemberAccessor;

                bool isSet;
                MappingSchema.MetadataProvider.GetPrimaryKeyOrder(om.TypeAccessor.OriginalType, typeExt, ma, out isSet);

                if (!isSet)
                {
                    list.Add(mm);
                }
            }

            return(list.ToArray());
        }
Ejemplo n.º 5
0
        protected internal virtual MemberMapper[] GetKeyFieldList(DbManager db, Type type)
        {
            var key = type.FullName + "$" + db.DataProvider.UniqueName;

            _keyListLock.EnterReadLock();
            MemberMapper[] mmList = null;
            try
            {
                mmList = (MemberMapper[])_keyList[key];
            }
            finally
            {
                _keyListLock.ExitReadLock();
            }
            if (mmList == null)
            {
                var typeExt = TypeExtension.GetTypeExtension(type, Extensions);
                var list    = new List <MemberOrder>();

                foreach (MemberMapper mm in db.MappingSchema.GetObjectMapper(type))
                {
                    if (mm.MapMemberInfo.SqlIgnore)
                    {
                        continue;
                    }

                    var ma = mm.MapMemberInfo.MemberAccessor;

                    if (TypeHelper.IsScalar(ma.Type))
                    {
                        bool isSet;
                        var  order = MappingSchema.MetadataProvider.GetPrimaryKeyOrder(type, typeExt, ma, out isSet);

                        if (isSet)
                        {
                            list.Add(new MemberOrder(mm, order));
                        }
                    }
                }

                list.Sort((x, y) => x.Order - y.Order);

                _keyListLock.EnterWriteLock();
                try
                {
                    _keyList[key] = mmList = new MemberMapper[list.Count];
                    for (var i = 0; i < list.Count; i++)
                    {
                        mmList[i] = list[i].MemberMapper;
                    }
                }
                finally
                {
                    _keyListLock.ExitWriteLock();
                }
            }

            return(mmList);
        }
Ejemplo n.º 6
0
        public override string GetTableName(Type type, ExtensionList extensions, out bool isSet)
        {
            var typeExt = TypeExtension.GetTypeExtension(type, extensions);
            var value   = typeExt.Attributes["TableName"].Value;

            if (value != null)
            {
                isSet = true;
                return(value.ToString());
            }

            return(base.GetTableName(type, extensions, out isSet));
        }
Ejemplo n.º 7
0
            protected Type GetObjectType()
            {
                for (var type = OriginalType.BaseType; type != null && type != typeof(object); type = type.BaseType)
                {
                    var extension = TypeExtension.GetTypeExtension(type, Parser.MappingSchema.Extensions);
                    var mapping   = Parser.MappingSchema.MetadataProvider.GetInheritanceMapping(type, extension);

                    if (mapping.Length > 0)
                    {
                        return(type);
                    }
                }

                return(OriginalType);
            }
Ejemplo n.º 8
0
        protected SqlQueryInfo CreateInsertSqlText(DbManager db, Type type)
        {
            TypeExtension        typeExt = TypeExtension.GetTypeExtension(type, Extensions);
            ObjectMapper         om      = db.MappingSchema.GetObjectMapper(type);
            List <MemberMapper>  list    = new List <MemberMapper>();
            StringBuilder        sb      = new StringBuilder();
            SqlQueryInfo         query   = new SqlQueryInfo(om);
            MetadataProviderBase mp      = MappingSchema.MetadataProvider;

            sb.AppendFormat("INSERT INTO {0} (\n",
                            db.DataProvider.Convert(GetTableName(type), ConvertType.NameToQueryTable));

            foreach (MemberMapper mm in GetFieldList(om))
            {
                // IT: This works incorrectly for complex mappers.
                //
                bool isSet;

                if (!mp.GetNonUpdatableFlag(type, typeExt, mm.ComplexMemberAccessor, out isSet) || !isSet)
                {
                    sb.AppendFormat("\t{0},\n",
                                    db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryField));
                    list.Add(mm);
                }
            }

            sb.Remove(sb.Length - 2, 1);

            sb.Append(") VALUES (\n");

            foreach (MemberMapper mm in list)
            {
                SqlQueryParameterInfo p = query.AddParameter(
                    db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryParameter).ToString(),
                    mm.Name);

                sb.AppendFormat("\t{0},\n", p.ParameterName);
            }

            sb.Remove(sb.Length - 2, 1);

            sb.Append(")");

            query.QueryText = sb.ToString();

            return(query);
        }
Ejemplo n.º 9
0
        public SqlTable([JetBrains.Annotations.NotNull] MappingSchema mappingSchema, Type objectType) : this()
        {
            if (mappingSchema == null)
            {
                throw new ArgumentNullException("mappingSchema");
            }

            bool isSet;

            Database     = mappingSchema.MetadataProvider.GetDatabaseName(objectType, mappingSchema.Extensions, out isSet);
            Owner        = mappingSchema.MetadataProvider.GetOwnerName(objectType, mappingSchema.Extensions, out isSet);
            Name         = mappingSchema.MetadataProvider.GetTableName(objectType, mappingSchema.Extensions, out isSet);
            ObjectType   = objectType;
            PhysicalName = Name;

            var typeExt = TypeExtension.GetTypeExtension(objectType, mappingSchema.Extensions);

            foreach (MemberMapper mm in mappingSchema.GetObjectMapper(objectType))
            {
                if (mm.MapMemberInfo.SqlIgnore == false)
                {
                    var ua =
                        mappingSchema.MetadataProvider.GetNonUpdatableAttribute(objectType, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                    var order = mappingSchema.MetadataProvider.GetPrimaryKeyOrder(objectType, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                    Fields.Add(new SqlField(
                                   mm.Type,
                                   mm.MemberName,
                                   mm.Name,
                                   mm.MapMemberInfo.Nullable,
                                   isSet ? order : int.MinValue,
                                   ua,
                                   mm));
                }
            }

            var identityField = GetIdentityField();

            if (identityField != null)
            {
                var om = mappingSchema.GetObjectMapper(ObjectType);
                var mm = om[identityField.Name, true];

                _sequenceAttributes = mm.MapMemberInfo.MemberAccessor.GetAttributes <SequenceNameAttribute>();
            }
        }
Ejemplo n.º 10
0
        protected override IBuildContext BuildMethodCall(ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo)
        {
            var sequence = builder.BuildSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]));
            var table    = sequence as TableBuilder.TableContext;

            if (table != null && table.InheritanceMapping.Count > 0)
            {
                var objectType = methodCall.Type.GetGenericArguments()[0];

                if (TypeHelper.IsSameOrParent(table.ObjectType, objectType))
                {
                    var predicate = builder.MakeIsPredicate(table, objectType);

                    if (predicate.GetType() != typeof(SqlQuery.Predicate.Expr))
                    {
                        sequence.SqlQuery.Where.SearchCondition.Conditions.Add(new SqlQuery.Condition(false, predicate));
                    }
                }
            }
            else
            {
                var toType   = methodCall.Type.GetGenericArguments()[0];
                var gargs    = TypeHelper.GetGenericArguments(methodCall.Arguments[0].Type, typeof(IQueryable <>));
                var fromType = gargs == null ? typeof(object) : gargs[0];

                if (toType.IsSubclassOf(fromType))
                {
                    for (var type = toType.BaseType; type != null && type != typeof(object); type = type.BaseType)
                    {
                        var extension = TypeExtension.GetTypeExtension(type, builder.MappingSchema.Extensions);
                        var mapping   = builder.MappingSchema.MetadataProvider.GetInheritanceMapping(type, extension);

                        if (mapping.Length > 0)
                        {
                            var predicate = MakeIsPredicate(builder, sequence, fromType, toType);

                            sequence.SqlQuery.Where.SearchCondition.Conditions.Add(new SqlQuery.Condition(false, predicate));

                            return(new OfTypeContext(sequence, methodCall));
                        }
                    }
                }
            }

            return(sequence);
        }
Ejemplo n.º 11
0
        protected internal virtual MemberMapper[] GetKeyFieldList(DbManager db, Type type)
        {
            string key = type.FullName + "$" + db.DataProvider.UniqueName;

            MemberMapper[] mmList = (MemberMapper[])_keyList[key];

            if (mmList == null)
            {
                TypeExtension      typeExt = TypeExtension.GetTypeExtension(type, Extensions);
                List <MemberOrder> list    = new List <MemberOrder>();

                foreach (MemberMapper mm in db.MappingSchema.GetObjectMapper(type))
                {
                    if (mm.MapMemberInfo.SqlIgnore)
                    {
                        continue;
                    }

                    MemberAccessor ma = mm.MapMemberInfo.MemberAccessor;

                    if (TypeHelper.IsScalar(ma.Type))
                    {
                        bool isSet;
                        int  order = MappingSchema.MetadataProvider.GetPrimaryKeyOrder(type, typeExt, ma, out isSet);

                        if (isSet)
                        {
                            list.Add(new MemberOrder(mm, order));
                        }
                    }
                }

                list.Sort(delegate(MemberOrder x, MemberOrder y) { return(x.Order - y.Order); });

                _keyList[key] = mmList = new MemberMapper[list.Count];

                for (int i = 0; i < list.Count; i++)
                {
                    mmList[i] = list[i].MemberMapper;
                }
            }

            return(mmList);
        }
Ejemplo n.º 12
0
        protected MemberMapper[] GetNonKeyFieldList(ObjectMapper om)
        {
            TypeExtension       typeExt = TypeExtension.GetTypeExtension(om.TypeAccessor.OriginalType, Extensions);
            List <MemberMapper> list    = new List <MemberMapper>();

            foreach (MemberMapper mm in om)
            {
                MemberAccessor ma = mm.MemberAccessor;

                bool isSet;
                MappingSchema.MetadataProvider.GetPrimaryKeyOrder(om.TypeAccessor.OriginalType, typeExt, ma, out isSet);

                if (!isSet)
                {
                    list.Add(mm);
                }
            }

            return(list.ToArray());
        }
Ejemplo n.º 13
0
        public virtual void Init(MappingSchema mappingSchema, Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            _typeAccessor  = TypeAccessor.GetAccessor(type);
            _mappingSchema = mappingSchema;
            _extension     = TypeExtension.GetTypeExtension(_typeAccessor.OriginalType, mappingSchema.Extensions);

            _inheritanceMapping.AddRange(GetInheritanceMapping());

            foreach (MemberAccessor ma in _typeAccessor)
            {
                Association a = GetAssociation(ma);

                if (a != null)
                {
                    _associations.Add(a);
                    continue;
                }

                if (GetMapIgnore(ma))
                {
                    continue;
                }

                MapFieldAttribute mapFieldAttr = ma.GetAttribute <MapFieldAttribute>();

                if (mapFieldAttr == null || (mapFieldAttr.OrigName == null && mapFieldAttr.Format == null))
                {
                    MapMemberInfo mi = new MapMemberInfo();

                    DbTypeAttribute dbTypeAttribute = ma.GetAttribute <DbTypeAttribute>();

                    if (dbTypeAttribute != null)
                    {
                        mi.DbType      = dbTypeAttribute.DbType;
                        mi.IsDbTypeSet = true;
                        if (dbTypeAttribute.Size != null)
                        {
                            mi.DbSize      = dbTypeAttribute.Size.Value;
                            mi.IsDbSizeSet = true;
                        }
                    }

                    mi.MemberAccessor             = ma;
                    mi.Type                       = ma.Type;
                    mi.MappingSchema              = mappingSchema;
                    mi.MemberExtension            = _extension[ma.Name];
                    mi.Name                       = GetFieldName(ma);
                    mi.MemberName                 = ma.Name;
                    mi.Storage                    = GetFieldStorage(ma);
                    mi.IsInheritanceDiscriminator = GetInheritanceDiscriminator(ma);
                    mi.Trimmable                  = GetTrimmable(ma);
                    mi.SqlIgnore                  = GetSqlIgnore(ma);
                    mi.MapValues                  = GetMapValues(ma);
                    mi.DefaultValue               = GetDefaultValue(ma);
                    mi.Nullable                   = GetNullable(ma);
                    mi.NullValue                  = GetNullValue(ma, mi.Nullable);

                    Add(CreateMemberMapper(mi));
                }
                else if (mapFieldAttr.OrigName != null)
                {
                    EnsureMapper(mapFieldAttr.MapName, ma.Name + "." + mapFieldAttr.OrigName);
                }
                else if (mapFieldAttr.Format != null)
                {
                    foreach (MemberMapper inner in _mappingSchema.GetObjectMapper(ma.Type))
                    {
                        EnsureMapper(string.Format(mapFieldAttr.Format, inner.Name), ma.Name + "." + inner.MemberName);
                    }
                }
            }

            foreach (AttributeExtension ae in _extension.Attributes["MapField"])
            {
                string mapName  = (string)ae["MapName"];
                string origName = (string)ae["OrigName"];

                if (mapName == null || origName == null)
                {
                    throw new MappingException(string.Format(
                                                   "Type '{0}' has invalid  extension. MapField MapName='{1}' OrigName='{2}'.",
                                                   type.FullName, mapName, origName));
                }

                EnsureMapper(mapName, origName);
            }

            MetadataProvider.EnsureMapper(TypeAccessor, MappingSchema, EnsureMapper);
        }
Ejemplo n.º 14
0
        protected SqlQueryInfo CreateUpdateSqlText(DbManager db, Type type, int nParameter)
        {
            var typeExt = TypeExtension.GetTypeExtension(type, Extensions);
            var om      = db.MappingSchema.GetObjectMapper(type);
            var sb      = new StringBuilder();
            var query   = new SqlQueryInfo(om);
            var mp      = MappingSchema.MetadataProvider;

            sb.Append("UPDATE\n\t");
            AppendTableName(sb, db, type);
            sb.Append("\nSET\n");

            var fields    = GetFieldList(om);
            var hasFields = false;

            foreach (var mm in fields)
            {
                bool isSet;

                var nonUpdatableAttribute = mp.GetNonUpdatableAttribute(type, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                if (nonUpdatableAttribute != null && isSet && nonUpdatableAttribute.OnUpdate == true)
                {
                    continue;
                }

                mp.GetPrimaryKeyOrder(type, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);

                if (isSet)
                {
                    continue;
                }

                hasFields = true;

                var p = query.AddParameter(
                    db.DataProvider.Convert(mm.Name + "_P", ConvertType.NameToQueryParameter).ToString(),
                    mm.Name);

                sb.AppendFormat("\t{0} = ", db.DataProvider.Convert(p.FieldName, ConvertType.NameToQueryField));

                if (nParameter < 0)
                {
                    sb.AppendFormat("{0},\n", p.ParameterName);
                }
                else
                {
                    sb.AppendFormat("\t{{{0}}},\n", nParameter++);
                }
            }

            if (!hasFields)
            {
                throw new DataAccessException(
                          string.Format("There are no fields to update in the type '{0}'.", query.ObjectType.FullName));
            }

            sb.Remove(sb.Length - 2, 1);

            AddWherePK(db, query, sb, nParameter);

            query.QueryText = sb.ToString();

            return(query);
        }
Ejemplo n.º 15
0
        public virtual void Init(MappingSchema mappingSchema, Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            _typeAccessor  = TypeAccessor.GetAccessor(type);
            _mappingSchema = mappingSchema;
            _extension     = TypeExtension.GetTypeExtension(
                _typeAccessor.OriginalType, mappingSchema.Extensions);

            foreach (MemberAccessor ma in _typeAccessor)
            {
                if (GetIgnore(ma))
                {
                    continue;
                }

                MapFieldAttribute mapFieldAttr = ma.GetAttribute <MapFieldAttribute>();

                if (mapFieldAttr == null || (mapFieldAttr.OrigName == null && mapFieldAttr.Format == null))
                {
                    MapMemberInfo mi = new MapMemberInfo();

                    mi.MemberAccessor  = ma;
                    mi.Type            = ma.Type;
                    mi.MappingSchema   = mappingSchema;
                    mi.MemberExtension = _extension[ma.Name];
                    mi.Name            = GetFieldName(ma);
                    mi.MemberName      = ma.Name;
                    mi.Trimmable       = GetTrimmable(ma);
                    mi.MapValues       = GetMapValues(ma);
                    mi.DefaultValue    = GetDefaultValue(ma);
                    mi.Nullable        = GetNullable(ma);
                    mi.NullValue       = GetNullValue(ma, mi.Nullable);

                    Add(CreateMemberMapper(mi));
                }
                else if (mapFieldAttr.OrigName != null)
                {
                    EnsureMapper(mapFieldAttr.MapName, ma.Name + "." + mapFieldAttr.OrigName);
                }
                else if (mapFieldAttr.Format != null)
                {
                    foreach (MemberMapper inner in _mappingSchema.GetObjectMapper(ma.Type))
                    {
                        EnsureMapper(string.Format(mapFieldAttr.Format, inner.Name), ma.Name + "." + inner.MemberName);
                    }
                }
            }

            foreach (AttributeExtension ae in _extension.Attributes["MapField"])
            {
                string mapName  = (string)ae["MapName"];
                string origName = (string)ae["OrigName"];

                if (mapName == null || origName == null)
                {
                    throw new MappingException(string.Format(
                                                   "Type '{0}' has invalid  extension. MapField MapName='{1}' OrigName='{2}'.",
                                                   type.FullName, mapName, origName));
                }

                EnsureMapper(mapName, origName);
            }

            MetadataProvider.EnsureMapper(this, EnsureMapper);
        }
Ejemplo n.º 16
0
        public override List <MapRelationBase> GetRelations(MappingSchema schema, ExtensionList typeExt, Type master, Type slave, out bool isSet)
        {
            var masterAccessor = TypeAccessor.GetAccessor(master);
            var slaveAccessor  = slave != null?TypeAccessor.GetAccessor(slave) : null;

            var relations = new List <MapRelationBase>();

            foreach (MemberAccessor ma in masterAccessor)
            {
                var attr = ma.GetAttribute <RelationAttribute>();

                if (attr == null || (slave != null && attr.Destination != slave && ma.Type != slave))
                {
                    continue;
                }

                if (slave == null)
                {
                    slaveAccessor = TypeAccessor.GetAccessor(attr.Destination ?? ma.Type);
                }


                var toMany = TypeHelper.IsSameOrParent(typeof(IEnumerable), ma.Type);

                if (toMany && attr.Destination == null)
                {
                    throw new InvalidOperationException("Destination type should be set for enumerable relations: " + ma.Type.FullName + "." + ma.Name);
                }

                var masterIndex = attr.MasterIndex;
                var slaveIndex  = attr.SlaveIndex;

                if (slaveIndex == null)
                {
                    var accessor = toMany ? masterAccessor : slaveAccessor;
                    var tex      = TypeExtension.GetTypeExtension(accessor.Type, typeExt);
                    var keys     = GetPrimaryKeyFields(schema, accessor, tex);

                    if (keys.Count > 0)
                    {
                        slaveIndex = new MapIndex(keys.ToArray());
                    }
                }

                if (slaveIndex == null)
                {
                    throw new InvalidOperationException("Slave index is not set for relation: " + ma.Type.FullName + "." + ma.Name);
                }

                if (masterIndex == null)
                {
                    masterIndex = slaveIndex;
                }

                var relation = new MapRelationBase(attr.Destination ?? ma.Type, slaveIndex, masterIndex, ma.Name);

                relations.Add(relation);
            }

            isSet = true;
            return(relations);
        }
Ejemplo n.º 17
0
        private IMapper GetObjectMapper(IObjectMapper mapper, ref int startIndex, TypeAccessor akTypeAccessor)
        {
            //Todo: Remove this Call!
            _extension = TypeExtension.GetTypeExtension(mapper.PropertyType /*_typeAccessor.OriginalType*/, MappingSchema.Extensions);

            Type mapperType    = mapper.PropertyType;
            var  objectMappers = new List <IObjectMapper>();

            TableDescription tableDescription = GetTableDescription(mapperType);

            lock (SetterHandlersLock)
            {
                if (!SettersHandlers.ContainsKey(mapperType))
                {
                    SettersHandlers.Add(mapperType, new Dictionary <string, SetHandler>());
                }

                if (!GettersHandlers.ContainsKey(mapperType))
                {
                    GettersHandlers.Add(mapperType, new Dictionary <string, GetHandler>());
                }
            }

            PropertyInfo[] properties = mapperType.GetProperties();

            MemberAccessor primaryKeyMemberAccessor = null;

            foreach (MemberAccessor ma in akTypeAccessor)
            {
                //  Setters
                lock (SetterHandlersLock)
                {
                    if (!SettersHandlers[mapper.PropertyType].ContainsKey(ma.Name))
                    {
                        SettersHandlers[mapper.PropertyType].Add(ma.Name, ma.SetValue);
                    }
                }

                if (GetPrimaryKey(ma) != null)
                {
                    primaryKeyMemberAccessor = ma;

                    lock (SetterHandlersLock)
                    {
                        if (!GettersHandlers[mapperType].ContainsKey(ma.Name))
                        {
                            GettersHandlers[mapperType].Add(ma.Name, ma.GetValue);
                        }
                    }
                    mapper.PrimaryKeyValueGetters.Add(GettersHandlers[mapperType][ma.Name]);
                    mapper.PrimaryKeyNames.Add(ma.Name);

                    if (mapper.Association != null && (mapper.Association.OtherKey == null || mapper.Association.OtherKey.Length == 0))
                    {
                        mapper.Association.OtherKey = new[] { ma.Name };
                    }
                }
            }
            if (primaryKeyMemberAccessor == null)
            {
                throw new Exception("PrimaryKey attribute not found on type: " + mapperType);
            }

            foreach (PropertyInfo prop in properties)
            {
                var ma = akTypeAccessor.First(x => x.Name == prop.Name);

                // Check if the accessor is an association
                var association = GetAssociation(ma);
                if (association != null)
                {
                    //  Getters for IObjectMapper
                    lock (SetterHandlersLock)
                        if (!GettersHandlers[mapperType].ContainsKey(prop.Name))
                        {
                            GettersHandlers[mapperType].Add(prop.Name, ma.GetValue);
                        }

                    bool          isCollection = prop.PropertyType.GetInterfaces().ToList().Contains(typeof(IList));
                    IObjectMapper propertiesMapping;
                    if (!isCollection)
                    {
                        // TODO Generate this instance using the CreateObjectMapperInstance method of fullMappingSchema
                        // _db.MappingSchema.CreateObjectMapperInstance(prop.PropertyType)

                        propertiesMapping = new FullObjectMapper(_db, _ignoreLazyLoad, _factoryType)
                        {
                            PropertyType = prop.PropertyType,
                            IsNullable   = association.CanBeNull,
                            Getter       = GettersHandlers[mapperType][prop.Name],
                        };
                    }
                    else
                    {
                        Type             listElementType            = GetGenericType(prop.PropertyType);
                        TableDescription colElementTableDescription = GetTableDescription(listElementType);

                        // TODO Generate this instance using the CreateObjectMapperInstance method of fullMappingSchema
                        propertiesMapping = new CollectionFullObjectMapper(_db, _factoryType)
                        {
                            PropertyType           = listElementType,
                            Getter                 = GettersHandlers[mapperType][prop.Name],
                            TableName              = colElementTableDescription.TableName,
                            PropertyCollectionType = prop.PropertyType,
                        };

                        if (mapper is FullObjectMapper)
                        {
                            ((FullObjectMapper)mapper).ColParent = true;
                        }
                    }

                    if (association.ThisKey == null || association.ThisKey.Length == 0)
                    {
                        association.ThisKey = new[] { primaryKeyMemberAccessor.Name }
                    }
                    ;

                    bool isLazy = false;
                    if (!_ignoreLazyLoad)
                    {
                        var lazy = GetLazyInstance(ma); // prop.GetCustomAttributes(typeof(LazyInstanceAttribute), true);
                        if (lazy)
                        {
                            isLazy = true;
                            mapper.ContainsLazyChild = true;

                            //  Getters
                            lock (SetterHandlersLock)
                                if (!GettersHandlers[mapperType].ContainsKey(primaryKeyMemberAccessor.Name))
                                {
                                    GettersHandlers[mapperType].Add(primaryKeyMemberAccessor.Name, primaryKeyMemberAccessor.GetValue);
                                }
                        }
                    }

                    propertiesMapping.Association  = association;
                    propertiesMapping.PropertyName = prop.Name;
                    propertiesMapping.IsLazy       = isLazy;
                    propertiesMapping.Setter       = SettersHandlers[mapperType][prop.Name];

                    if (propertiesMapping.IsLazy)
                    {
                        propertiesMapping.ParentKeyGetter = GettersHandlers[mapperType][primaryKeyMemberAccessor.Name];
                    }
                    objectMappers.Add(propertiesMapping);
                }
                else
                {
                    var mapIgnore = GetMapIgnore(ma);
                    if (mapIgnore)
                    {
                        continue;
                    }

                    var    mapField   = GetMapField(ma);
                    string columnName = mapField != null ? mapField.MapName : prop.Name;

                    var map = new ValueMapper
                    {
                        PropertyName    = prop.Name,
                        PropertyType    = prop.PropertyType,
                        DataReaderIndex = startIndex,
                        Setter          = SettersHandlers[mapperType][prop.Name],
                        TableName       = tableDescription.TableName,
                        ColumnName      = columnName,
                    };

                    var mapColumnName = map.GetColumnName(columnName);
                    map.ColumnAlias = columnName == mapColumnName ? null : mapColumnName;

                    mapper.PropertiesMapping.Add(map);

                    var pkField = GetPrimaryKey(ma);
                    if (pkField != null)
                    {
                        mapper.DataReaderIndex = startIndex;
                    }

                    startIndex++;
                }
            }

            foreach (IObjectMapper objMap in objectMappers)
            {
                #region Check mapping recursion

                IObjectMapper cel = mapper;
                while (cel != null)
                {
                    if (mapper.PropertyType == objMap.PropertyType)
                    {
                        continue;
                    }

                    cel = (IObjectMapper)cel.ParentMapping;
                }

                #endregion

                objMap.ParentMapping = mapper;
                mapper.PropertiesMapping.Add(GetObjectMapper(objMap, ref startIndex, MappingSchema.GetObjectMapper(objMap.PropertyType).TypeAccessor));
            }

            return(mapper);
        }
Ejemplo n.º 18
0
        public override List <MapRelationBase> GetRelations(MappingSchema schema, ExtensionList typeExt, Type master, Type slave, out bool isSet)
        {
            List <MapRelationBase> relations = new List <MapRelationBase>();
            TypeExtension          ext       = typeExt != null ? typeExt[master] : TypeExtension.Null;

            isSet = ext != TypeExtension.Null;

            if (!isSet)
            {
                return(relations);
            }

            TypeAccessor ta = TypeAccessor.GetAccessor(master);

            foreach (MemberExtension mex in ext.Members)
            {
                AttributeExtensionCollection relationInfos = mex.Attributes[TypeExtension.NodeName.Relation];

                if (relationInfos == AttributeExtensionCollection.Null)
                {
                    continue;
                }

                string         destinationTypeName = relationInfos[0][TypeExtension.AttrName.DestinationType, string.Empty].ToString();
                Type           destinationType     = slave;
                MemberAccessor ma     = ta[mex.Name];
                bool           toMany = TypeHelper.IsSameOrParent(typeof(IEnumerable), ma.Type);

                if (destinationTypeName == string.Empty)
                {
                    if (toMany)
                    {
                        throw new InvalidOperationException("Destination type should be set for enumerable relations: " + ma.Type.FullName + "." + ma.Name);
                    }

                    destinationType = ma.Type;
                }
                else
                {
                    if (!destinationTypeName.Contains(","))
                    {
                        destinationTypeName += ", " + ta.OriginalType.Assembly.FullName;
                    }

                    try
                    {
                        destinationType = Type.GetType(destinationTypeName, true);
                    }
                    catch (TypeLoadException ex)
                    {
                        throw new InvalidOperationException(
                                  "Unable to load type by name: " + destinationTypeName
                                  + "\n may be assembly is not specefied, please see Type.GetType(string typeName) documentation",
                                  ex);
                    }
                }

                if (slave != null && !TypeHelper.IsSameOrParent(slave, destinationType))
                {
                    continue;
                }

                List <string> masterIndexFields = new List <string>();
                List <string> slaveIndexFields  = new List <string>();

                foreach (AttributeExtension ae in relationInfos[0].Attributes[TypeExtension.NodeName.MasterIndex])
                {
                    masterIndexFields.Add(ae[TypeExtension.AttrName.Name].ToString());
                }

                foreach (AttributeExtension ae in relationInfos[0].Attributes[TypeExtension.NodeName.SlaveIndex])
                {
                    slaveIndexFields.Add(ae[TypeExtension.AttrName.Name].ToString());
                }


                if (slaveIndexFields.Count == 0)
                {
                    TypeAccessor  accessor = toMany ? ta : TypeAccessor.GetAccessor(destinationType);
                    TypeExtension tex      = TypeExtension.GetTypeExtension(accessor.Type, typeExt);

                    slaveIndexFields = GetPrimaryKeyFields(schema, accessor, tex);
                }

                if (slaveIndexFields.Count == 0)
                {
                    throw new InvalidOperationException("Slave index is not set for relation: " + ma.Type.FullName + "." + ma.Name);
                }

                MapIndex slaveIndex  = new MapIndex(slaveIndexFields.ToArray());
                MapIndex masterIndex = masterIndexFields.Count > 0 ? new MapIndex(masterIndexFields.ToArray()) : slaveIndex;

                MapRelationBase mapRelation = new MapRelationBase(destinationType, slaveIndex, masterIndex, mex.Name);

                relations.Add(mapRelation);
            }

            isSet = relations.Count > 0;
            return(relations);
        }