コード例 #1
0
        private static string GetTypeString(PocoColumn column)
        {
            IColumnInfo typeInfo;
            var         typeCode = TypeCodec.GetColumnTypeCodeInfo(column.ColumnType, out typeInfo);

            return(GetTypeString(typeCode, typeInfo));
        }
コード例 #2
0
        internal static object ProcessMapper(IMapper mapper, PocoColumn pc, object value)
        {
            if (mapper == null)
            {
                return(value);
            }
            var converter = mapper.GetToDbConverter(pc.ColumnType, pc.MemberInfo);

            return(converter != null?converter(value) : value);
        }
コード例 #3
0
 public override object ProcessDefaultMappings(PocoColumn pocoColumn, object value)
 {
     if (pocoColumn.MemberInfoData.MemberType == typeof(byte[]) && value == null)
     {
         return(new SqlParameter("__bytes", SqlDbType.VarBinary, -1)
         {
             Value = DBNull.Value
         });
     }
     return(base.ProcessDefaultMappings(pocoColumn, value));
 }
コード例 #4
0
        private static string GetTypeString(PocoColumn column, ColumnTypeCode typeCode, IColumnInfo typeInfo)
        {
            if (typeInfo == null)
            {
                //Is a single type
                return(typeCode.ToString().ToLower());
            }
            string typeName    = null;
            var    frozenKey   = column != null && column.HasFrozenKey;
            var    frozenValue = column != null && column.HasFrozenValue;

            if (typeInfo is MapColumnInfo)
            {
                var mapInfo = (MapColumnInfo)typeInfo;
                typeName = "map<" +
                           WrapFrozen(frozenKey, GetTypeString(null, mapInfo.KeyTypeCode, mapInfo.KeyTypeInfo)) +
                           ", " +
                           WrapFrozen(frozenValue, GetTypeString(null, mapInfo.ValueTypeCode, mapInfo.ValueTypeInfo)) +
                           ">";
            }
            else if (typeInfo is SetColumnInfo)
            {
                var setInfo = (SetColumnInfo)typeInfo;
                typeName = "set<" +
                           WrapFrozen(frozenKey, GetTypeString(null, setInfo.KeyTypeCode, setInfo.KeyTypeInfo)) +
                           ">";
            }
            else if (typeInfo is ListColumnInfo)
            {
                var setInfo = (ListColumnInfo)typeInfo;
                typeName = "list<" +
                           WrapFrozen(frozenValue, GetTypeString(null, setInfo.ValueTypeCode, setInfo.ValueTypeInfo)) +
                           ">";
            }
            else if (typeInfo is TupleColumnInfo)
            {
                var tupleInfo = (TupleColumnInfo)typeInfo;
                typeName = "tuple<" +
                           string.Join(", ", tupleInfo.Elements.Select(e => GetTypeString(null, e.TypeCode, e.TypeInfo))) +
                           ">";
            }
            else if (typeInfo is UdtColumnInfo)
            {
                var udtInfo = (UdtColumnInfo)typeInfo;
                // Escape keyspace and name from the UDT
                typeName = string.Join(".", udtInfo.Name.Split('.').Select(k => "\"" + k + "\""));
            }

            if (typeName == null)
            {
                throw new NotSupportedException(string.Format("Type {0} is not supported", typeCode));
            }
            return(WrapFrozen(column != null && column.IsFrozen, typeName));
        }
コード例 #5
0
        public IManyColumnBuilder <T2> Many <T2>(Expression <Func <T, IList <T2> > > property)
        {
            var members = MemberHelper <T> .GetMembers(property);

            var columnDefinition = new ColumnDefinition()
            {
                MemberInfo = members.Last()
            };
            var builder = new ManyColumnBuilder <T2>(columnDefinition);
            var key     = PocoColumn.GenerateKey(members);

            _columnDefinitions[key] = columnDefinition;
            return(builder);
        }
コード例 #6
0
        public PocoData(Type t, IMapper mapper, Cache<string, Type> aliasToTypeCache)
            : this()
        {
            aliasToType = aliasToTypeCache;
            type = t;
            Mapper = mapper;
            TableInfo = TableInfo.FromPoco(t);

            // Call column mapper
            if (Mapper != null)
                Mapper.GetTableInfo(t, TableInfo);

            var alias = CreateAlias(type.Name, type);
            TableInfo.AutoAlias = alias;
            var index = 0;

            // Work out bound properties
            Columns = new Dictionary<string, PocoColumn>(StringComparer.OrdinalIgnoreCase);
            foreach (var mi in ReflectionUtils.GetFieldsAndPropertiesForClasses(t))
            {
                ColumnInfo ci = ColumnInfo.FromMemberInfo(mi);
                if (ci.IgnoreColumn)
                    continue;

                var pc = new PocoColumn();
                pc.TableInfo = TableInfo;
                pc.MemberInfo = mi;
                pc.ColumnName = ci.ColumnName;
                pc.ResultColumn = ci.ResultColumn;
                pc.ForceToUtc = ci.ForceToUtc;
                pc.ComputedColumn = ci.ComputedColumn;
                pc.ColumnType = ci.ColumnType;
                pc.ColumnAlias = ci.ColumnAlias;
                pc.VersionColumn = ci.VersionColumn;
                pc.VersionColumnType = ci.VersionColumnType;

                if (Mapper != null && !Mapper.MapMemberToColumn(mi, ref pc.ColumnName, ref pc.ResultColumn))
                    continue;

                pc.AutoAlias = alias + "_" + index++;

                // Store it
                if (!Columns.ContainsKey(pc.ColumnName))
                    Columns.Add(pc.ColumnName, pc);
            }

            // Build column list for automatic select
            QueryColumns = Columns.Where(c => !c.Value.ResultColumn).ToArray();
        }
コード例 #7
0
        /// <summary>
        /// Tries to evaluate the current expression and add it as a projection
        /// </summary>
        private Expression AddProjection(Expression node, PocoColumn column = null)
        {
            var value = Expression.Lambda(node).Compile().DynamicInvoke();

            if (column == null)
            {
                column = _pocoData.GetColumnByMemberName(_currentBindingName.Get());
                if (column == null)
                {
                    throw new CqlLinqNotSupportedException(node, _parsePhase.Get());
                }
            }
            _projections.Add(Tuple.Create(column, value, ExpressionType.Assign));
            return(node);
        }
コード例 #8
0
        public IConditionItem SetColumn(PocoColumn column)
        {
            if (_parameters.Count > 0)
            {
                _isYoda = true;
            }

            if (!_allowMultipleColumns && _columns.Count == 1)
            {
                throw new InvalidOperationException("Multiple columns is not supported on a single binary expression");
            }

            _columns.Add(column);
            return(this);
        }
コード例 #9
0
        public IColumnBuilder <T2> Column <T2>(Expression <Func <T, T2> > property)
        {
            MemberInfo[] members = MemberHelper <T> .GetMembers(property);

            MemberInfo       memberInfo       = members.Last();
            ColumnDefinition columnDefinition = new ColumnDefinition()
            {
                MemberInfo = memberInfo
            };
            ColumnBuilder <T2> builder = new ColumnBuilder <T2>(columnDefinition);
            string             key     = PocoColumn.GenerateKey(members);

            this._columnDefinitions[key] = columnDefinition;
            return(builder);
        }
コード例 #10
0
        private static string GetTypeString(Serializer serializer, PocoColumn column)
        {
            if (column.IsCounter)
            {
                return("counter");
            }
            IColumnInfo typeInfo;
            var         typeCode = serializer.GetCqlType(column.ColumnType, out typeInfo);
            var         typeName = GetTypeString(column, typeCode, typeInfo);

            if (column.IsStatic)
            {
                return(typeName + " static");
            }
            return(typeName);
        }
コード例 #11
0
        public static PocoMember FindMember(List <PocoMember> pocoMembers, string name)
        {
            return(pocoMembers
                   .Where(x => x.ReferenceType == ReferenceType.None)
                   .FirstOrDefault(x =>
            {
                PocoColumn col = x.PocoColumn;

                if (col != null && PropertyMapper.IsEqual(name, col.ColumnAlias ?? col.ColumnName))
                {
                    return true;
                }

                return PropertyMapper.IsEqual(name, x.Name);
            }));
        }
コード例 #12
0
        private static string GetTypeString(PocoColumn column)
        {
            if (column.IsCounter)
            {
                return("counter");
            }
            IColumnInfo typeInfo;
            var         typeCode = TypeCodec.GetColumnTypeCodeInfo(column.ColumnType, out typeInfo);
            var         typeName = GetTypeString(column, typeCode, typeInfo);

            if (column.IsStatic)
            {
                return(typeName + " static");
            }
            return(typeName);
        }
コード例 #13
0
        private static Mappings CreateMappings(ConventionScannerSettings scannerSettings, Type[] typesOverride)
        {
            var types  = typesOverride ?? FindTypes(scannerSettings);
            var config = new Dictionary <Type, TypeDefinition>();

            foreach (var type in types)
            {
                var pocoDefn = new TypeDefinition(type)
                {
                    AutoIncrement   = scannerSettings.PrimaryKeysAutoIncremented(type),
                    PrimaryKey      = scannerSettings.PrimaryKeysNamed(type),
                    TableName       = scannerSettings.TablesNamed(type),
                    PersistedType   = scannerSettings.PersistedTypesBy(type),
                    SequenceName    = scannerSettings.SequencesNamed(type),
                    UseOutputClause = scannerSettings.UseOutputClauseWhere(type),
                    ExplicitColumns = true
                };

                foreach (var columnDefinition in GetColumnDefinitions(scannerSettings, type, new List <MemberInfo>()))
                {
                    var key = PocoColumn.GenerateKey(columnDefinition.MemberInfoChain);
                    if (!pocoDefn.ColumnConfiguration.ContainsKey(key))
                    {
                        pocoDefn.ColumnConfiguration.Add(key, columnDefinition);
                    }
                }

                config.Add(type, pocoDefn);
            }

            foreach (var mappingOverride in scannerSettings.MappingOverrides)
            {
                MergeOverrides(config, mappingOverride);
            }

            //if (scannerSettings.OverrideWithAttributes)
            //{
            //    MergeAttributeOverrides(config);
            //}

            var pocoMappings = new Mappings {
                Config = config
            };

            return(pocoMappings);
        }
コード例 #14
0
        private static string GetTypeString(Serializer serializer, PocoColumn column)
        {
            string typeName;

            if (!column.IsCounter)
            {
                var typeCode = serializer.GetCqlType(column.ColumnType, out var typeInfo);
                typeName = GetTypeString(column, typeCode, typeInfo);
            }
            else
            {
                typeName = "counter";
            }

            if (column.IsStatic)
            {
                return(typeName + " static");
            }

            return(typeName);
        }
コード例 #15
0
        public SqlBackedTable(string connectionString, string namespacePrefix, string schemaName, string tableName, bool includeCache)
        {
            SchemaName = schemaName;
            TableName = tableName;
            NamespacePrefix = namespacePrefix;
            IncludeCache = includeCache;

            Columns = new List<PocoColumn>();
            using (var cn = new SqlConnection(connectionString)) {
                DatabaseName = cn.Database;
                cn.Open();

                List<string> schemas = new List<string>();
                string path = Program.MapPath(@"..\sql\columns.sql");
                using (var cmd = new SqlCommand(File.ReadAllText(path), cn)) {
                    cmd.Parameters.AddWithValue("@TABLE_SCHEMA", schemaName);
                    cmd.Parameters.AddWithValue("@TABLE_NAME", tableName);

                    bool multiColumnPk = false;
                    using (SqlDataReader reader = cmd.ExecuteReader()) {
                        while (reader.Read()) {
                            var c = new PocoColumn(reader);
                            Columns.Add(c);
                            // We only allow for single column, int, based primary keys
                            // Since otherwise we need to change the types on our Get methods
                            if (!multiColumnPk && c.IsPrimaryKey && c.DotNetType == "int") {

                                if (PrimaryKey != null) {
                                    PrimaryKey = null;
                                    multiColumnPk = true;
                                } else {

                                    PrimaryKey = c;
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
        public Dictionary <string, JoinData> GetJoinExpressions(Expression expression, string tableAlias, JoinType joinType)
        {
            IEnumerable <MemberInfo>      memberInfos     = MemberChainHelper.GetMembers(expression);
            List <PocoMember>             members         = this._pocoData.Members;
            Dictionary <string, JoinData> joinExpressions = new Dictionary <string, JoinData>();

            foreach (MemberInfo memberInfo in memberInfos)
            {
                PocoMember pocoMember = members
                                        .Where(x => x.ReferenceType != ReferenceType.None)
                                        .Single(x => x.MemberInfoData.MemberInfo == memberInfo);

                PocoColumn pocoColumn1 = pocoMember.PocoColumn;
                PocoMember pocoMember2 = pocoMember.PocoMemberChildren.Single(x => x.Name == pocoMember.ReferenceMemberName);
                PocoColumn pocoColumn2 = pocoMember2.PocoColumn;

                pocoColumn2.TableInfo.AutoAlias = tableAlias ?? pocoColumn2.TableInfo.AutoAlias;

                string onSql = this._database.DatabaseType.EscapeTableName(pocoColumn1.TableInfo.AutoAlias)
                               + "." + this._database.DatabaseType.EscapeSqlIdentifier(pocoColumn1.ColumnName)
                               + " = " + this._database.DatabaseType.EscapeTableName(pocoColumn2.TableInfo.AutoAlias)
                               + "." + this._database.DatabaseType.EscapeSqlIdentifier(pocoColumn2.ColumnName);

                if (!joinExpressions.ContainsKey(onSql))
                {
                    joinExpressions.Add(onSql, new JoinData()
                    {
                        OnSql          = onSql,
                        PocoMember     = pocoMember,
                        PocoMemberJoin = pocoMember2,
                        PocoMembers    = pocoMember.PocoMemberChildren,
                        JoinType       = joinType
                    });
                }

                members = pocoMember.PocoMemberChildren;
            }

            return(joinExpressions);
        }
コード例 #17
0
        public static Func <object, object> GetConverter(PocoData pocoData, PocoColumn pocoColumn, Type sourceType, Type desType)
        {
            var converter = MappingHelper.GetConverter(pocoData.Mapper, pocoColumn, sourceType, desType);

            return(converter);
        }
コード例 #18
0
ファイル: PropertyMapper.cs プロジェクト: limengchang/frapid
        private bool MapValue(GroupResult <PosName> posName, DbDataReader reader, Func <object, object> converter, object instance, PocoColumn pocoColumn, object defaultValue)
        {
            if (!reader.IsDBNull(posName.Key.Pos))
            {
                object value = converter != null?converter(reader.GetValue(posName.Key.Pos)) : reader.GetValue(posName.Key.Pos);

                pocoColumn.SetValue(instance, value);
                return(true);
            }

            if (this._mappingOntoExistingInstance && defaultValue == null)
            {
                pocoColumn.SetValue(instance, null);
            }

            return(false);
        }
コード例 #19
0
        public FluentMappingsPocoData(Type t, TypeDefinition typeConfig, IMapper mapper)
        {
            Mapper    = mapper;
            type      = t;
            TableInfo = new TableInfo();

            // Get the table name
            var a = typeConfig.TableName ?? "";

            TableInfo.TableName = a.Length == 0 ? t.Name : a;

            // Get the primary key
            a = typeConfig.PrimaryKey ?? "";
            TableInfo.PrimaryKey = a.Length == 0 ? "ID" : a;

            a = typeConfig.SequenceName ?? "";
            TableInfo.SequenceName = a.Length == 0 ? null : a;

            TableInfo.AutoIncrement = typeConfig.AutoIncrement ?? true;

            // Set autoincrement false if primary key has multiple columns
            TableInfo.AutoIncrement = TableInfo.AutoIncrement ? !TableInfo.PrimaryKey.Contains(',') : TableInfo.AutoIncrement;

            // Call column mapper
            if (mapper != null)
            {
                mapper.GetTableInfo(t, TableInfo);
            }

            // Work out bound properties
            bool explicitColumns = typeConfig.ExplicitColumns ?? false;

            Columns = new Dictionary <string, PocoColumn>(StringComparer.OrdinalIgnoreCase);
            foreach (var mi in ReflectionUtils.GetFieldsAndPropertiesForClasses(t))
            {
                // Work out if properties is to be included
                var isColumnDefined = typeConfig.ColumnConfiguration.ContainsKey(mi.Name);
                if (explicitColumns && !isColumnDefined)
                {
                    continue;
                }

                if (isColumnDefined && (typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.HasValue && typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.Value))
                {
                    continue;
                }

                var pc = new PocoColumn();
                pc.MemberInfo = mi;

                // Work out the DB column name
                if (isColumnDefined)
                {
                    var colattr = typeConfig.ColumnConfiguration[mi.Name];
                    pc.ColumnName = colattr.DbColumnName;
                    if (colattr.ResultColumn.HasValue && colattr.ResultColumn.Value)
                    {
                        pc.ResultColumn = true;
                    }
                    else if (colattr.VersionColumn.HasValue && colattr.VersionColumn.Value)
                    {
                        pc.VersionColumn = true;
                    }

                    if (colattr.ForceUtc.HasValue && colattr.ForceUtc.Value)
                    {
                        pc.ForceToUtc = true;
                    }

                    if (TableInfo.PrimaryKey.Split(',').Contains(mi.Name))
                    {
                        TableInfo.PrimaryKey = (pc.ColumnName ?? mi.Name) + ",";
                    }

                    pc.ColumnType = colattr.DbColumnType;
                }
                if (pc.ColumnName == null)
                {
                    pc.ColumnName = mi.Name;
                    if (mapper != null && !mapper.MapMemberToColumn(mi, ref pc.ColumnName, ref pc.ResultColumn))
                    {
                        continue;
                    }
                }

                // Store it
                Columns.Add(pc.ColumnName, pc);
            }

            // Trim trailing slash if built using Property names
            TableInfo.PrimaryKey = TableInfo.PrimaryKey.TrimEnd(',');

            // Build column list for automatic select
            QueryColumns = (from c in Columns where !c.Value.ResultColumn select c.Key).ToArray();
        }
コード例 #20
0
        public FluentMappingsPocoData(Type t, TypeDefinition typeConfig, IMapper mapper, Cache<string, Type> aliasCache)
        {
            AliasToType = aliasCache;
            Mapper = mapper;
            type = t;
            TableInfo = new TableInfo();

            // Get the table name
            var a = typeConfig.TableName ?? "";
            TableInfo.TableName = a.Length == 0 ? t.Name : a;

            // Get the primary key
            a = typeConfig.PrimaryKey ?? "";
            TableInfo.PrimaryKey = a.Length == 0 ? "ID" : a;

            a = typeConfig.SequenceName ?? "";
            TableInfo.SequenceName = a.Length == 0 ? null : a;

            TableInfo.AutoIncrement = typeConfig.AutoIncrement ?? true;

            // Set autoincrement false if primary key has multiple columns
            TableInfo.AutoIncrement = TableInfo.AutoIncrement ? !TableInfo.PrimaryKey.Contains(',') : TableInfo.AutoIncrement;

            // Call column mapper
            if (mapper != null)
                mapper.GetTableInfo(t, TableInfo);

            var alias = CreateAlias(type.Name, type);
            TableInfo.AutoAlias = alias;
            var index = 0;

            // Work out bound properties
            bool explicitColumns = typeConfig.ExplicitColumns ?? false;
            Columns = new Dictionary<string, PocoColumn>(StringComparer.OrdinalIgnoreCase);
            var originalPK = TableInfo.PrimaryKey.Split(',');
            foreach (var mi in ReflectionUtils.GetFieldsAndPropertiesForClasses(t))
            {
                // Work out if properties is to be included
                var isColumnDefined = typeConfig.ColumnConfiguration.ContainsKey(mi.Name);
                if (explicitColumns && !isColumnDefined) continue;

                if (isColumnDefined && (typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.HasValue && typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.Value))
                    continue;

                var pc = new PocoColumn();
                pc.TableInfo = TableInfo;
                pc.MemberInfo = mi;
                pc.AutoAlias = alias + "_" + index++;

                // Work out the DB column name
                if (isColumnDefined)
                {
                    var colattr = typeConfig.ColumnConfiguration[mi.Name];
                    pc.ColumnName = colattr.DbColumnName;
                    pc.ColumnAlias = colattr.DbColumnAlias;
                    if (colattr.ResultColumn.HasValue && colattr.ResultColumn.Value)
                        pc.ResultColumn = true;
                    else if (colattr.VersionColumn.HasValue && colattr.VersionColumn.Value)
                    {
                        pc.VersionColumn = true;
                        pc.VersionColumnType = colattr.VersionColumnType ?? VersionColumnType.Number;
                    }
                    else if (colattr.ComputedColumn.HasValue && colattr.ComputedColumn.Value)
                        pc.ComputedColumn = true;

                    if (colattr.ForceUtc.HasValue && colattr.ForceUtc.Value)
                        pc.ForceToUtc = true;

                    for (int i = 0; i < originalPK.Length; i++)
                    {
                        if (originalPK[i].Equals(mi.Name, StringComparison.OrdinalIgnoreCase))
                            originalPK[i] = (pc.ColumnName ?? mi.Name);
                    }

                    pc.ColumnType = colattr.DbColumnType;
                }
                if (pc.ColumnName == null)
                {
                    pc.ColumnName = mi.Name;
                    if (mapper != null && !mapper.MapMemberToColumn(mi, ref pc.ColumnName, ref pc.ResultColumn))
                        continue;
                }

                // Store it
                if (!Columns.ContainsKey(pc.ColumnName))
                    Columns.Add(pc.ColumnName, pc);
            }

            // Recombine the primary key
            TableInfo.PrimaryKey = String.Join(",", originalPK);

            // Build column list for automatic select
            QueryColumns = Columns.Where(x => !x.Value.ResultColumn).ToArray();
        }
コード例 #21
0
ファイル: PropertyMapper.cs プロジェクト: zzia615/NPoco
        private bool MapValue(GroupResult <PosName> posName, object[] values, Func <object, object> converter, object instance, PocoColumn pocoColumn, object defaultValue)
        {
            var value = values[posName.Key.Pos];

            if (!Equals(value, DBNull.Value))
            {
                pocoColumn.SetValue(instance, converter != null ? converter(value) : value);
                return(true);
            }

            if (_mappingOntoExistingInstance && defaultValue == null)
            {
                pocoColumn.SetValue(instance, null);
            }

            return(false);
        }
コード例 #22
0
ファイル: IRowMapper.cs プロジェクト: schotime/NPoco
 public static Func<object, object> GetConverter(PocoData pocoData, PocoColumn pocoColumn, Type sourceType, Type desType)
 {
     var converter = MappingHelper.GetConverter(pocoData.Mapper, pocoColumn, sourceType, desType);
     return converter;
 }
コード例 #23
0
        private async Task <int> ExecuteUpdateAsync(string tableName, string primaryKeyName, object poco, object primaryKeyValue, IEnumerable <string> columns)
        {
            try {
                await OpenSharedConnectionAsync().ConfigureAwait(false);

                try {
                    using (var cmd = CreateCommand(_sharedConnection, "", new object[0])) {
                        var type = poco.GetType();
                        var pd   = PocoData.ForObject(poco, primaryKeyName);
                        var sql  = update.Get(Tuple.Create(type, _sqlHelper._sqlType), () => {
                            var sb    = new StringBuilder();
                            var index = 0;
                            foreach (var i in pd.Columns)
                            {
                                if (String.Compare(i.Value.ColumnName, primaryKeyName, StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    continue;
                                }
                                if (i.Value.ResultColumn)
                                {
                                    continue;
                                }

                                // Build the sql
                                if (index > 0)
                                {
                                    sb.Append(", ");
                                }
                                sb.AppendFormat("{0} = {1}{2}", _provider.EscapeSqlIdentifier(i.Value.ColumnName), _paramPrefix, index++);
                            }

                            return(string.Format("UPDATE {0} SET {1} WHERE {2} = {3}{4}",
                                                 _provider.EscapeTableName(tableName), sb.ToString(), _provider.EscapeSqlIdentifier(primaryKeyName), _paramPrefix, index++));
                        });

                        cmd.CommandText = sql;

                        foreach (var i in pd.Columns)
                        {
                            if (i.Value.ResultColumn)
                            {
                                continue;
                            }
                            if (string.Compare(i.Value.ColumnName, primaryKeyName, true) == 0)
                            {
                                if (primaryKeyValue == null)
                                {
                                    primaryKeyValue = i.Value.GetValue(poco);
                                }
                                continue;
                            }
                            AddParam(cmd, i.Value.GetValue(poco), i.Value.PropertyInfo);
                        }

                        // Find the property info for the primary key
                        PropertyInfo pkpi = null;
                        if (primaryKeyName != null)
                        {
                            PocoColumn col = pd.Columns.FirstOrDefault(q => q.Value.ColumnName == primaryKeyName).Value;
                            if (col != null)
                            {
                                pkpi = col.PropertyInfo;
                            }
                            else
                            {
                                pkpi = new { Id = primaryKeyValue }
                            }.GetType().GetProperties()[0];
                        }
                        AddParam(cmd, primaryKeyValue, pkpi);

                        DoPreExecute(cmd);

                        // Do it
                        var retv = await((SqlCommand)cmd).ExecuteNonQueryAsync().ConfigureAwait(false);
                        OnExecutedCommand(cmd);
                        return(retv);
                    }
コード例 #24
0
ファイル: PropertyMapper.cs プロジェクト: schotime/NPoco
        private bool MapValue(GroupResult<PosName> posName, object[] values, Func<object, object> converter, object instance, PocoColumn pocoColumn, object defaultValue)
        {
            var value = values[posName.Key.Pos];
            if (!Equals(value, DBNull.Value))
            {
                pocoColumn.SetValue(instance, converter != null ? converter(value) : value);
                return true;
            }

            if (_mappingOntoExistingInstance && defaultValue == null)
            {
                pocoColumn.SetValue(instance, null);
            }

            return false;
        }
コード例 #25
0
        public FluentMappingsPocoData(Type t, TypeDefinition typeConfig, IMapper mapper)
        {
            Mapper = mapper;
            type = t;
            TableInfo = new TableInfo();

            // Get the table name
            var a = typeConfig.TableName ?? "";
            TableInfo.TableName = a.Length == 0 ? t.Name : a;

            // Get the primary key
            a = typeConfig.PrimaryKey ?? "";
            TableInfo.PrimaryKey = a.Length == 0 ? "ID" : a;

            a = typeConfig.SequenceName ?? "";
            TableInfo.SequenceName = a.Length == 0 ? null : a;

            TableInfo.AutoIncrement = typeConfig.AutoIncrement ?? true;

            // Set autoincrement false if primary key has multiple columns
            TableInfo.AutoIncrement = TableInfo.AutoIncrement ? !TableInfo.PrimaryKey.Contains(',') : TableInfo.AutoIncrement;

            // Call column mapper
            if (mapper != null)
                mapper.GetTableInfo(t, TableInfo);

            // Work out bound properties
            bool explicitColumns = typeConfig.ExplicitColumns ?? false;
            Columns = new Dictionary<string, PocoColumn>(StringComparer.OrdinalIgnoreCase);
            foreach (var mi in ReflectionUtils.GetFieldsAndPropertiesForClasses(t))
            {
                // Work out if properties is to be included
                var isColumnDefined = typeConfig.ColumnConfiguration.ContainsKey(mi.Name);
                if (explicitColumns && !isColumnDefined) continue;

                if (isColumnDefined && (typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.HasValue && typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.Value))
                    continue;

                var pc = new PocoColumn();
                pc.MemberInfo = mi;

                // Work out the DB column name
                if (isColumnDefined)
                {
                    var colattr = typeConfig.ColumnConfiguration[mi.Name];
                    pc.ColumnName = colattr.DbColumnName;
                    if (colattr.ResultColumn.HasValue && colattr.ResultColumn.Value)
                        pc.ResultColumn = true;
                    else if (colattr.VersionColumn.HasValue && colattr.VersionColumn.Value)
                        pc.VersionColumn = true;

                    if (colattr.ForceUtc.HasValue && colattr.ForceUtc.Value)
                        pc.ForceToUtc = true;

                    if (TableInfo.PrimaryKey.Split(',').Contains(mi.Name))
                        TableInfo.PrimaryKey = (pc.ColumnName ?? mi.Name) + ",";

                    pc.ColumnType = colattr.DbColumnType;

                }
                if (pc.ColumnName == null)
                {
                    pc.ColumnName = mi.Name;
                    if (mapper != null && !mapper.MapMemberToColumn(mi, ref pc.ColumnName, ref pc.ResultColumn))
                        continue;
                }

                // Store it
                Columns.Add(pc.ColumnName, pc);
            }

            // Trim trailing slash if built using Property names
            TableInfo.PrimaryKey = TableInfo.PrimaryKey.TrimEnd(',');

            // Build column list for automatic select
            QueryColumns = (from c in Columns where !c.Value.ResultColumn select c.Key).ToArray();
        }
コード例 #26
0
 public IConditionItem SetColumn(PocoColumn column)
 {
     throw new NotSupportedException("Setting column is not supported on IF EXISTS condition");
 }
コード例 #27
0
        internal static IEnumerable <PosName> ConvertFromNewConvention(this IEnumerable <PosName> posNames, PocoData pocoData)
        {
            var    allMembers        = pocoData.GetAllMembers().ToList();
            var    scopedPocoMembers = pocoData.Members;
            string prefix            = null;

            foreach (var posName in posNames)
            {
                if (posName.Name == "npoco")
                {
                    scopedPocoMembers.Clear();
                    prefix = null;
                    continue;
                }

                if (posName.Name.StartsWith(SplitPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    prefix = posName.Name.Substring(SplitPrefix.Length);
                    var relevantMembers = allMembers.SingleOrDefault(x => string.Equals(PocoColumn.GenerateKey(x.MemberInfoChain), prefix, StringComparison.OrdinalIgnoreCase));
                    if (relevantMembers != null)
                    {
                        scopedPocoMembers = relevantMembers.PocoMemberChildren;
                    }

                    continue;
                }

                var member = FindMember(scopedPocoMembers, prefix, posName.Name);
                if (member != null && member.PocoColumn != null)
                {
                    posName.Name = member.PocoColumn.MemberInfoKey;
                }
                else
                {
                    posName.Name = PocoDataBuilder.JoinStrings(prefix, posName.Name);
                }

                yield return(posName);
            }
        }
コード例 #28
0
        public FluentMappingsPocoData(Type t, TypeDefinition typeConfig, IMapper mapper)
        {
            Mapper    = mapper;
            type      = t;
            TableInfo = new TableInfo();

            // Get the table name
            var a = typeConfig.TableName ?? "";

            TableInfo.TableName = a.Length == 0 ? t.Name : a;

            // Get the primary key
            a = typeConfig.PrimaryKey ?? "";
            TableInfo.PrimaryKey = a.Length == 0 ? "ID" : a;

            a = typeConfig.SequenceName ?? "";
            TableInfo.SequenceName = a.Length == 0 ? null : a;

            TableInfo.AutoIncrement = typeConfig.AutoIncrement ?? true;

            // Set autoincrement false if primary key has multiple columns
            TableInfo.AutoIncrement = TableInfo.AutoIncrement ? !TableInfo.PrimaryKey.Contains(',') : TableInfo.AutoIncrement;

            // Call column mapper
            if (mapper != null)
            {
                mapper.GetTableInfo(t, TableInfo);
            }

            var alias = CreateAlias(type.Name, type);

            TableInfo.AutoAlias = alias;
            var index = 0;

            // Work out bound properties
            bool explicitColumns = typeConfig.ExplicitColumns ?? false;

            Columns = new Dictionary <string, PocoColumn>(StringComparer.OrdinalIgnoreCase);
            var originalPK = TableInfo.PrimaryKey.Split(',');

            foreach (var mi in ReflectionUtils.GetFieldsAndPropertiesForClasses(t))
            {
                // Work out if properties is to be included
                var isColumnDefined = typeConfig.ColumnConfiguration.ContainsKey(mi.Name);
                if (explicitColumns && !isColumnDefined)
                {
                    continue;
                }

                if (isColumnDefined && (typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.HasValue && typeConfig.ColumnConfiguration[mi.Name].IgnoreColumn.Value))
                {
                    continue;
                }

                var pc = new PocoColumn();
                pc.TableInfo  = TableInfo;
                pc.MemberInfo = mi;
                pc.AutoAlias  = alias + "_" + index++;

                // Work out the DB column name
                if (isColumnDefined)
                {
                    var colattr = typeConfig.ColumnConfiguration[mi.Name];
                    pc.ColumnName  = colattr.DbColumnName;
                    pc.ColumnAlias = colattr.DbColumnAlias;
                    if (colattr.ResultColumn.HasValue && colattr.ResultColumn.Value)
                    {
                        pc.ResultColumn = true;
                    }
                    else if (colattr.VersionColumn.HasValue && colattr.VersionColumn.Value)
                    {
                        pc.VersionColumn = true;
                    }
                    else if (colattr.ComputedColumn.HasValue && colattr.ComputedColumn.Value)
                    {
                        pc.ComputedColumn = true;
                    }

                    if (colattr.ForceUtc.HasValue && colattr.ForceUtc.Value)
                    {
                        pc.ForceToUtc = true;
                    }

                    for (int i = 0; i < originalPK.Length; i++)
                    {
                        if (originalPK[i].Equals(mi.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            originalPK[i] = (pc.ColumnName ?? mi.Name);
                        }
                    }

                    pc.ColumnType = colattr.DbColumnType;
                }
                if (pc.ColumnName == null)
                {
                    pc.ColumnName = mi.Name;
                    if (mapper != null && !mapper.MapMemberToColumn(mi, ref pc.ColumnName, ref pc.ResultColumn))
                    {
                        continue;
                    }
                }

                // Store it
                Columns.Add(pc.ColumnName, pc);
            }

            // Recombine the primary key
            TableInfo.PrimaryKey = String.Join(",", originalPK);

            // Build column list for automatic select
            QueryColumns = Columns.Where(x => !x.Value.ResultColumn).ToArray();
        }
コード例 #29
0
ファイル: PropertyMapper.cs プロジェクト: joonhwan/NPoco
        private bool MapValue(GroupResult<PosName> posName, DbDataReader reader, Func<object, object> converter, object instance, PocoColumn pocoColumn, object defaultValue)
        {
            if (!reader.IsDBNull(posName.Key.Pos))
            {
                var value = converter != null ? converter(reader.GetValue(posName.Key.Pos)) : reader.GetValue(posName.Key.Pos);
                pocoColumn.SetValue(instance, value);
                return true;
            }

            if (_mappingOntoExistingInstance && defaultValue == null)
            {
                pocoColumn.SetValue(instance, null);
            }

            return false;
        }