Ejemplo n.º 1
0
        // Constructs input to check against dictionary contents when looking up an input.
        public Table(ForeignKeyAttribute foreignKeyAttribute, TableAttribute tableAttribute)
        {
            foreignKeyAttribute.IsNotNull(nameof(foreignKeyAttribute));

            this.HasTableAttribute = tableAttribute != null;
            this.CatalogueName = tableAttribute?.CatalogueName;
            this.TableName = foreignKeyAttribute.PrimaryTableName;
            this.Schema = foreignKeyAttribute.Schema;
        }
Ejemplo n.º 2
0
        // Constructs a value to add to dictionary.
        public Table(TableAttribute tableAttribute)
        {
            tableAttribute.IsNotNull(nameof(tableAttribute));

            this.TableName = tableAttribute.Name;
            this.Schema = tableAttribute.Schema;
            this.CatalogueName = tableAttribute.CatalogueName;
            this.HasTableAttribute = true;
        }
Ejemplo n.º 3
0
        internal EntityMapping CreateMapping()
        {
            var entity = new EntityMapping { entityType = EntityType };
            if (table == null)
                table = entity.entityType.GetAttribute<TableAttribute>(false);
            if (table != null)
            {
                entity.tableName = table.Name.IsNullOrEmpty()
                    ? entity.entityType.Name
                    : table.Name;
                entity.@readonly = table.Readonly;
                entity.schema = table.Schema;
                entity.databaseName = table.DatabaseName;
                entity.serverName = table.Server;
            }
            else
                entity.tableName = entity.entityType.Name;

            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;

            var allMembers = new Dictionary<MemberInfo, MemberMapping>();
            foreach (var k in members.Keys)
                allMembers[k] = new MemberMapping(k, members[k], entity);

            var items = from m in entity.entityType
                       .GetFields(bindingFlags)
                       .Where(p => !members.ContainsKey(p))
                       .Where(p => !IgnoreMembers.Contains(p))
                       .Where(p => !p.HasAttribute<IgnoreAttribute>(true))
                       .Where(p => !p.Name.Contains("k__BackingField"))
                       .Where(p => !p.IsInitOnly)
                       .Cast<MemberInfo>()
                       .Union(entity.entityType
                           .GetProperties(bindingFlags)
                           .Where(p => !members.ContainsKey(p))
                           .Where(p => !IgnoreMembers.Contains(p))
                           .Where(p => p.CanRead && p.CanWrite)
                           .Where(p => !p.HasAttribute<IgnoreAttribute>(true))
                           .Cast<MemberInfo>()
                           ).Distinct()
                        let att = m.GetAttribute<MemberAttribute>(true)
                        select new NLite.Data.Mapping.MemberMapping(m, att, entity);

            foreach (var item in items)
                allMembers[item.member] = item;

            entity.innerMappingMembers = allMembers.Values.ToArray();
            return entity;
        }
        public MappingSchema GetSchema(Lock @lock)
        {
            var schema  = new MappingSchema(@lock.Id.ToString(), _baseSchema);
            var builder = schema.GetFluentMappingBuilder();

            foreach (var dataObjectType in _dataObjectTypes)
            {
                var baseTable = _baseSchema.GetAttribute <TableAttribute>(dataObjectType);
                if (baseTable != null)
                {
                    var attribute = new TableAttribute {
                        Name = $"{baseTable.Schema}_{baseTable.Name ?? dataObjectType.Name}_{@lock.Id}", Schema = "WebApp", IsColumnAttributeRequired = false
                    };
                    builder.HasAttribute(dataObjectType, attribute);
                }
            }

            if (@lock.IsNew)
            {
                InitializeMappingSchema(schema, @lock);
            }

            return(schema);
        }
Ejemplo n.º 5
0
        public ApplicationObject GetOutgoingQueueMetadata(InfoBase infoBase)
        {
            Type template = typeof(DatabaseOutgoingMessage);

            TableAttribute table = template.GetCustomAttribute <TableAttribute>();

            if (table == null || string.IsNullOrWhiteSpace(table.Name))
            {
                //ShowErrorMessage($"TableAttribute is not defined for template type \"{template.FullName}\".");
                return(null);
            }

            ApplicationObject queue = FindMetadataObjectByName(infoBase, table.Name);

            if (queue == null)
            {
                //ShowErrorMessage($"Metadata object \"{table.Name}\" is not found.");
                return(null);
            }

            IDatabaseInterfaceValidator validator = new DatabaseInterfaceValidator();

            if (!validator.OutgoingInterfaceIsValid(queue, out List <string> errors))
            {
                //ShowErrorMessage($"{table.Name}");
                //foreach (string error in errors)
                //{
                //    ShowErrorMessage(error);
                //}
                return(null);
            }

            BuildOutgoingQueueSelectScript(queue, template, 1000);

            return(queue);
        }
Ejemplo n.º 6
0
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                var attribute = new TableAttribute(this.TableName, this.PartitionKey, this.RowKey);

                attribute.Filter = Filter;
                var take = this.Take;

                if (take.HasValue)
                {
                    attribute.Take = take.Value;
                }
                attributes.Add(attribute);

                string account = Context.GetMetadataValue <string>("connection");

                if (!string.IsNullOrEmpty(account))
                {
                    attributes.Add(new StorageAccountAttribute(account));
                }

                return(attributes);
            }
Ejemplo n.º 7
0
        public override string Delete <TEntity>(TEntity entity)
        {
            DbContext.Parameters = new Dictionary <string, object>();
            DbContext.TableName  = TableAttribute.GetName(typeof(TEntity));
            PropertyInfo[] propertyInfos = GetPropertiesDicByType(typeof(TEntity));
            //get property which is key
            var property = propertyInfos.Where(t => t.GetCustomAttribute(typeof(KeyAttribute), true) is KeyAttribute)?.FirstOrDefault();

            if (property == null)
            {
                throw new TableKeyNotFoundException($"table '{DbContext.TableName}' not found key column");
            }

            string colunmName = property.Name;
            var    value      = property.GetValue(entity);

            if (property.GetCustomAttribute(typeof(ColumnAttribute), true) is ColumnAttribute columnAttr)
            {
                colunmName = columnAttr.GetName(property.Name);
            }

            DbContext.Parameters.AddOrUpdate($"@t{colunmName}", value);
            return(DbContext.SqlStatement = $"DELETE t FROM {DbContext.TableName} t WHERE t.{colunmName} = @t{colunmName}".TrimEnd());
        }
Ejemplo n.º 8
0
 /// <summary>
 /// 获得 Table 名称
 /// </summary>
 #region protected string GetTableName(Type type)
 protected string GetTableName(Type type)
 {
     try
     {
         TableAttribute TableAttr = GetTableAttr(type);
         return(TableAttr.Name);
     }
     catch (TypeLoadException ex)
     {
         throw ex;
     }
     catch (ArgumentNullException ex)
     {
         throw ex;
     }
     catch (ArgumentException ex)
     {
         throw ex;
     }
     catch (InvalidOperationException ex)
     {
         throw ex;
     }
 }
        /// <summary>
        /// 从缓存中获取数据,如果没有,则后台执行扫描表任务
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="dbContext"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        internal List <TEntity> GetEntitiesFromCache <TEntity>(Expression <Func <TEntity, bool> > filter) where TEntity : class
        {
            //1.检查是否开启了Table缓存
            if (!DbContext.OpenTableCache)
            {
                return(null);
            }

            //2.如果TableCache里面有该缓存键,则直接获取
            if (CacheStorageManager.IsExist(GetTableCacheKey(TableAttribute.GetName(typeof(TEntity))), out List <TEntity> entities))
            {
                DbContext.IsFromCache = true;
                return(entities.Where(filter.Compile()).ToList());
            }

            //3.则判断是否需要对该表进行扫描(含有TableCachingAttribute的标记的类才可以有扫描全表的权限)
            if (TableCachingAttribute.IsExistTaleCaching(typeof(TEntity), out TimeSpan tableCacheTimeSpan))
            {
                //执行扫描全表数据任务
                ScanTableBackground <TEntity>(tableCacheTimeSpan);
            }

            return(null);
        }
Ejemplo n.º 10
0
Archivo: DBEx.cs Proyecto: tfwcn/blog
        /// <summary>
        /// 对象转DataTable
        /// </summary>
        public static DataTable ModelToDataTable(this object obj, bool?dbCanWrite)
        {
            Type objType = obj.GetType();
            //获取表名
            string         tableName      = objType.Name;
            TableAttribute tableAttribute = Attribute.GetCustomAttribute(objType, typeof(TableAttribute)) as TableAttribute;

            if (tableAttribute != null && !String.IsNullOrEmpty(tableAttribute.Name))
            {
                tableName = tableAttribute.Name;
            }
            DataTable         dt     = new DataTable(tableName);
            List <DataColumn> pkList = new List <DataColumn>();

            foreach (var propertieInfo in objType.GetPropertiesPGS(dbCanWrite))
            {
                //获取字段名
                string          colName         = propertieInfo.Name;
                KeyAttribute    keyAttribute    = Attribute.GetCustomAttribute(propertieInfo, typeof(KeyAttribute)) as KeyAttribute;
                ColumnAttribute columnAttribute = Attribute.GetCustomAttribute(propertieInfo, typeof(ColumnAttribute)) as ColumnAttribute;
                if (columnAttribute != null && !String.IsNullOrEmpty(columnAttribute.Name))
                {
                    colName = columnAttribute.Name;
                }
                DataColumn col = dt.Columns.Add(colName, (propertieInfo.PropertyType.IsGenericType && propertieInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) ? propertieInfo.PropertyType.GetGenericArguments()[0] : propertieInfo.PropertyType);
                if (keyAttribute != null)
                {
                    pkList.Add(col);
                }
            }
            if (pkList.Count > 0)
            {
                dt.PrimaryKey = pkList.ToArray();
            }
            return(dt);
        }
Ejemplo n.º 11
0
        public override void DoBulkInsert <T>(Table <T> table, List <T> rows, IDbConnection connection)
        {
            int pageSize = UseBulkInsert[table];
            //ProjectionData projData = ProjectionData.FromReflectedType(typeof(T));
            ProjectionData projData    = AttribHelper.GetProjectionData(typeof(T));
            TableAttribute tableAttrib = typeof(T).GetCustomAttributes(false).OfType <TableAttribute>().Single();

            //build "INSERT INTO products (ProductName, SupplierID, CategoryID, QuantityPerUnit)"
            string header = "INSERT INTO " + tableAttrib.Name + " " + InsertClauseBuilder.InsertRowHeader(projData);

            foreach (List <T> page in Page.Paginate(rows, pageSize))
            {
                int                     numFieldsAdded = 0;
                StringBuilder           sbValues       = new StringBuilder(" VALUES ");
                List <IDbDataParameter> paramList      = new List <IDbDataParameter>();

                IDbCommand cmd = connection.CreateCommand();

                //package up all fields in N rows:
                string separator = "";
                foreach (T row in page)
                {
                    //prepare values = "(?P1, ?P2, ?P3, ?P4)"
                    string values =
                        InsertClauseBuilder.InsertRowFields(this, cmd, row, projData, paramList, ref numFieldsAdded);
                    sbValues.Append(separator).Append(values);
                    separator = ", ";
                }

                string sql = header + sbValues; //'INSET t1 (field1) VALUES (11),(12)'
                cmd.CommandText = sql;
                paramList.ForEach(param => cmd.Parameters.Add(param));

                int result = cmd.ExecuteNonQuery();
            }
        }
Ejemplo n.º 12
0
        private static string ConstructCopySql(Type entity, TableAttribute tableAttribute, RelatedEntityAttribute relatedAttribute, int keyValue)
        {
            FieldNamesCache.TryGetValue(entity.FullName ?? throw new InvalidOperationException(), out var fieldNames);

            if (string.IsNullOrEmpty(fieldNames))
            {
                var fields = entity.GetProperties();
                fieldNames = string.Join(", ", fields.Select(x => $"[{x.Name}]").ToArray());
                FieldNamesCache.Add(entity.FullName, fieldNames);
            }

            var sql = new StringBuilder();

            if (!ConstrainDisabledEntities.Contains(entity.FullName))
            {
                sql.AppendLine($"ALTER TABLE [daes_{_dbPrefix}].[{tableAttribute.TableSchema}].[{tableAttribute.TableName}] NOCHECK CONSTRAINT ALL");
                ConstrainDisabledEntities.Add(entity.FullName);
            }

            if (tableAttribute.HasIdentity)
            {
                sql.AppendLine($"SET IDENTITY_INSERT [daes_{_dbPrefix}].[{tableAttribute.TableSchema}].[{tableAttribute.TableName}] ON ");
            }

            sql.AppendLine($@"INSERT INTO [daes_{_dbPrefix}].[{tableAttribute.TableSchema}].[{tableAttribute.TableName}] ({fieldNames}) ");
            sql.AppendLine($@"SELECT {fieldNames} FROM [saes_{_dbPrefix}].[{tableAttribute.TableSchema}].[{tableAttribute.TableName}] src ");
            sql.AppendLine($@"WHERE {tableAttribute.PrimaryKey} = {keyValue}  ");
            sql.AppendLine($@"AND NOT EXISTS(SELECT 1 FROM [daes_{_dbPrefix}].[{tableAttribute.TableSchema}].[{tableAttribute.TableName}] dst WHERE dst.{tableAttribute.PrimaryKey} = src.{tableAttribute.PrimaryKey})");

            if (tableAttribute.HasIdentity)
            {
                sql.AppendLine($"SET IDENTITY_INSERT [daes_{_dbPrefix}].[{tableAttribute.TableSchema}].[{tableAttribute.TableName}] OFF ");
            }

            return(sql.ToString());
        }
Ejemplo n.º 13
0
        public static string GetCommands(EntityStatus entityState, TableAttribute table)
        {
            string command = string.Empty;

            switch (entityState)
            {
            case EntityStatus.Added:
                command = string.Format(DataResource.Operation_AddCommands, table.Schema, table.Name);
                break;

            case EntityStatus.Modified:
                command = string.Format(DataResource.Operation_UpdateCommands, table.Schema, table.Name);
                break;

            case EntityStatus.Deleted:
                command = string.Format(DataResource.Operation_DeleteCommands, table.Schema, table.Name);
                break;

            case EntityStatus.Selected:
                command = string.Format(DataResource.Query_SelectCommand, table.Schema, table.Name);
                break;
            }
            return(command);
        }
        /// <summary>
        /// 后台扫描全表数据
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="dbContext">上下文</param>
        /// <param name="tableCacheTimeSpan">tableCache过期时间</param>
        private void ScanTableBackground <TEntity>(TimeSpan tableCacheTimeSpan) where TEntity : class
        {
            string scanKey = $"{BankinateConst.CacheKey_TableScanning}{DbContext.CollectionName}";

            //1.判断正在扫描键是否存在,如果存在,则返回null,继续等待扫描任务完成
            if (CacheStorageManager.IsExist(scanKey))
            {
                return;
            }
            //2.如果没有扫描键,则执行后台扫描任务
            Task.Run(() =>
            {
                //设置扫描键,标识当前正在进行扫描
                CacheStorageManager.Put(scanKey, 1, BankinateConst.SpanScaningKeyExpiredTime);
                //对扫描任务加锁,防止多线程环境多次执行任务
                lock (tableScaningLocker)
                {
                    var tableName = TableAttribute.GetName(typeof(TEntity));
                    //双重校验当前缓存是否存在TableCache,防止多个进程在锁外等待,所释放后再次执行
                    if (CacheStorageManager.IsExist(GetTableCacheKey(tableName)))
                    {
                        return;
                    }
                    //如果过期时间为0,则取上下文的过期时间
                    TimeSpan timeSpan = tableCacheTimeSpan == TimeSpan.Zero ? DbContext.TableCacheExpiredTimeSpan : tableCacheTimeSpan;
                    //执行扫描全表任务,并将结果存入缓存中
                    var data = DbContext.GetFullCollectionData <TEntity>();
                    if (data != null)
                    {
                        CacheStorageManager.Put(GetTableCacheKey(tableName), data, DbContext.TableCacheExpiredTimeSpan);
                    }
                }
                //将扫描键移除,表示已经扫描完成
                CacheStorageManager.Delete(scanKey);
            });
        }
Ejemplo n.º 15
0
        public (string tblName, string keyName) MyTableNameAndKey(Type t)
        {
            string         tblName = "", keyName = "";
            TableAttribute ta = (TableAttribute)t.GetCustomAttribute(typeof(TableAttribute));

            if (ta != null)
            {
                tblName = ta.Name;
            }

            var properties = t.GetProperties();

            foreach (var property in properties)
            {
                var          pAttributes = property.GetCustomAttributes(false);
                KeyAttribute ka          = (KeyAttribute)property.GetCustomAttribute(typeof(KeyAttribute));
                if (ka != null)
                {
                    keyName = property.Name;
                    break;
                }
            }
            return(tblName, keyName);
        }
Ejemplo n.º 16
0
        private List <AuditLog> GetAuditRecordsForChange(DbEntityEntry dbEntry, int?userId)
        {
            List <AuditLog> result = new List <AuditLog>();

            DateTime changeTime = DateTime.Now;

            // Get the Table() attribute, if one exists
            //TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
            TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), true).SingleOrDefault() as TableAttribute;

            // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
            string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;

            // Get primary key value (If you have more than one key column, this will need to be adjusted)
            string keyName = dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

            if (dbEntry.State == EntityState.Added)
            {
                try
                {
                    base.SaveChanges();
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}",
                                                   validationError.PropertyName,
                                                   validationError.ErrorMessage);
                        }
                    }
                }
                // For Inserts, just add the whole record
                // If the entity implements IDescribableEntity, use the description from Describe(), otherwise use ToString()
                result.Add(new AuditLog()
                {
                    AuditLogId      = Guid.NewGuid(),
                    EventType       = "I", // Added/Inserted
                    TableName       = tableName,
                    PrimaryKeyName  = keyName,
                    PrimaryKeyValue = dbEntry.GetDatabaseValues().GetValue <object>(keyName).ToString(),  // Again, adjust this if you have a multi-column key

                    //ColumnName = "*ALL",    // Or make it nullable, whatever you want
                    //NewValue = dbEntry.CurrentValues.ToObject().ToString(),
                    CreatedUser = userId,
                    UpdatedDate = changeTime,
                }
                           );
            }
            else if (dbEntry.State == EntityState.Deleted)
            {
                // Same with deletes, do the whole record, and use either the description from Describe() or ToString()
                result.Add(new AuditLog()
                {
                    AuditLogId      = Guid.NewGuid(),
                    EventType       = "D", // Deleted
                    TableName       = tableName,
                    PrimaryKeyName  = keyName,
                    PrimaryKeyValue = dbEntry.OriginalValues.GetValue <object>(keyName).ToString(),
                    //ColumnName = "*ALL",
                    // NewValue = (dbEntry.OriginalValues.ToObject() is IDescribableEntity) ? (dbEntry.OriginalValues.ToObject() as IDescribableEntity).Describe() : dbEntry.OriginalValues.ToObject().ToString(),
                    CreatedUser = userId,
                    UpdatedDate = changeTime
                }
                           );
            }
            else if (dbEntry.State == EntityState.Modified)
            {
                foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
                {
                    var originalValue = dbEntry.GetDatabaseValues().GetValue <object>(propertyName) == null ? null : dbEntry.GetDatabaseValues().GetValue <object>(propertyName).ToString();
                    var newValue      = dbEntry.CurrentValues.GetValue <object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue <object>(propertyName).ToString();
                    // For updates, we only want to capture the columns that actually changed
                    // if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(), dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()))
                    //if (!object.Equals(dbEntry.GetDatabaseValues().GetValue<object>(propertyName).ToString(), dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()))
                    if (!(originalValue == newValue))
                    {
                        result.Add(new AuditLog()
                        {
                            AuditLogId      = Guid.NewGuid(),
                            EventType       = "U", // Modified/Updated
                            TableName       = tableName,
                            PrimaryKeyName  = keyName,
                            PrimaryKeyValue = dbEntry.OriginalValues.GetValue <object>(keyName).ToString(),
                            ColumnName      = propertyName,
                            OldValue        = originalValue,
                            NewValue        = newValue,
                            CreatedUser     = userId,
                            UpdatedDate     = changeTime
                        });
                    }
                }
            }
            // Otherwise, don't do anything, we don't care about Unchanged or Detached entities

            return(result);
        }
Ejemplo n.º 17
0
 public static void Schema_Set_NullOrWhitespaceValue_ThrowsArgumentException(string value)
 {
     TableAttribute attribute = new TableAttribute("Perspicacia Tick");
     Assert.Throws<ArgumentException>(null, () => attribute.Schema = value);
 }
Ejemplo n.º 18
0
        public TableAttribute GetEntityTableAttribute(Type type)
        {
            TableAttribute attr = null;

            if (_orm.Aop.ConfigEntity != null)
            {
                var aope = new Aop.ConfigEntityEventArgs(type);
                _orm.Aop.ConfigEntity(_orm, aope);
                attr = aope.ModifyResult;
            }
            if (attr == null)
            {
                attr = new TableAttribute();
            }
            if (dicConfigEntity.TryGetValue(type, out var trytb))
            {
                if (!string.IsNullOrEmpty(trytb.Name))
                {
                    attr.Name = trytb.Name;
                }
                if (!string.IsNullOrEmpty(trytb.OldName))
                {
                    attr.OldName = trytb.OldName;
                }
                if (!string.IsNullOrEmpty(trytb.SelectFilter))
                {
                    attr.SelectFilter = trytb.SelectFilter;
                }
                if (trytb._DisableSyncStructure != null)
                {
                    attr._DisableSyncStructure = trytb.DisableSyncStructure;
                }
            }
            var attrs = type.GetCustomAttributes(typeof(TableAttribute), false);

            foreach (var tryattrobj in attrs)
            {
                var tryattr = tryattrobj as TableAttribute;
                if (tryattr == null)
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(tryattr.Name))
                {
                    attr.Name = tryattr.Name;
                }
                if (!string.IsNullOrEmpty(tryattr.OldName))
                {
                    attr.OldName = tryattr.OldName;
                }
                if (!string.IsNullOrEmpty(tryattr.SelectFilter))
                {
                    attr.SelectFilter = tryattr.SelectFilter;
                }
                if (tryattr._DisableSyncStructure != null)
                {
                    attr._DisableSyncStructure = tryattr.DisableSyncStructure;
                }
            }
            if (!string.IsNullOrEmpty(attr.Name))
            {
                return(attr);
            }
            if (!string.IsNullOrEmpty(attr.OldName))
            {
                return(attr);
            }
            if (!string.IsNullOrEmpty(attr.SelectFilter))
            {
                return(attr);
            }
            if (attr._DisableSyncStructure != null)
            {
                return(attr);
            }
            return(null);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 根据条件得到实体对象集合
        /// 参数设置类似:queryCondition=" and Name='abc' and Age=23";orderBy=" ID desc,Age asc"
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queryCondition"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public IList <T> GetEntitiesByQueryCondition(string queryCondition, string orderBy = null)
        {
            IList <T> entityList = new List <T>();

            Type columnType = typeof(ColumnAttribute);

            object[] tableAttributeArray = typeof(T).GetCustomAttributes(typeof(TableAttribute), false);
            if (tableAttributeArray.Length == 0)
            {
                return(entityList);
            }

            TableAttribute ta        = tableAttributeArray[0] as TableAttribute;
            string         tableName = ta.TableName;


            string sql = string.Empty;

            if (string.IsNullOrEmpty(queryCondition))
            {
                sql = "select * from [" + tableName + "] ";
            }
            else
            {
                sql = "select * from [" + tableName + "] where 1=1 " + queryCondition;
            }
            if (!string.IsNullOrEmpty(orderBy))
            {
                sql += sql + " order by " + orderBy;
            }

            SqlDataReader sdr = null;

            try
            {
                sdr = SqlHelper.ExecuteReader(sql, CommandType.Text);
                while (sdr.Read())
                {
                    T entity = Activator.CreateInstance <T>();
                    foreach (PropertyInfo info in typeof(T).GetProperties())
                    {
                        string columnName = (info.GetCustomAttributes(columnType, false)[0] as ColumnAttribute).ColumnName;
                        //给属性赋值
                        if (sdr[columnName] != null)
                        {
                            info.SetValue(entity, Convert.ChangeType(sdr[columnName], info.PropertyType), null);
                        }
                    }
                    entityList.Add(entity);
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (sdr != null && !sdr.IsClosed)
                {
                    sdr.Close();
                }
            }
            return(entityList);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 根据条件和分页条件得到实体对象集合
        /// 参数设置类似:queryCondition=" and Name='abc' and Age=23";orderBy=" ID desc,Age asc"
        /// </summary>
        /// <param name="pageHelper"></param>
        /// <param name="queryCondition"></param>
        /// <param name="orderBy"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public IList <T> GetEntitiesByQueryConditionPaged(PageHelper pageHelper, string queryCondition, string orderBy = null)
        {
            IList <T> entityList = new List <T>();

            Type columnType = typeof(ColumnAttribute);

            object[] tableAttributeArray = typeof(T).GetCustomAttributes(typeof(TableAttribute), false);
            if (tableAttributeArray.Length == 0)
            {
                return(entityList);
            }

            TableAttribute ta            = tableAttributeArray[0] as TableAttribute;
            string         tableName     = ta.TableName;
            string         primaryColumn = ta.PrimaryKeyColumn;


            string rowIdColumn = string.Empty;

            if (string.IsNullOrEmpty(orderBy) && string.IsNullOrEmpty(primaryColumn))
            {
                return(entityList);
            }
            else if (!string.IsNullOrEmpty(orderBy))
            {
                rowIdColumn = "Row_number() over (order by " + orderBy + ") as RowID";
            }
            else
            {
                rowIdColumn = "Row_number() over (order by " + primaryColumn + " asc) as RowID";
            }

            int rowMin = pageHelper.PageSize * pageHelper.PageIndex;
            int rowMax = pageHelper.PageSize * (pageHelper.PageIndex + 1);

            string sqlRecord = string.Empty;
            string sqlCount  = string.Empty;

            if (string.IsNullOrEmpty(queryCondition))
            {
                sqlRecord = "select * from (select " + rowIdColumn + ",* from [" + tableName + "] ) as t where RowID>" + rowMin + " and RowID<=" + rowMax;
                sqlCount  = "select Count(1) as RecordCount from [" + tableName + "]";
            }
            else
            {
                sqlRecord = "select * from (select " + rowIdColumn + ",* from [" + tableName + "] where  " + queryCondition + " ) as t where RowID>" + rowMin + " and RowID<=" + rowMax;
                sqlCount  = "select Count(1) as RecordCount from [" + tableName + "] where " + queryCondition;
            }

            string        sql = sqlRecord + ";" + sqlCount;
            SqlDataReader sdr = null;

            try
            {
                sdr = SqlHelper.ExecuteReader(sql, CommandType.Text);
                while (sdr.Read())
                {
                    T entity = Activator.CreateInstance <T>();
                    foreach (PropertyInfo info in typeof(T).GetProperties())
                    {
                        string columnName = (info.GetCustomAttributes(columnType, false)[0] as ColumnAttribute).ColumnName;
                        //给属性赋值
                        if (sdr[columnName] != null)
                        {
                            info.SetValue(entity, Convert.ChangeType(sdr[columnName], info.PropertyType), null);
                        }
                    }
                    entityList.Add(entity);
                }

                if (sdr.NextResult() && sdr.Read())
                {
                    object Count = sdr["RecordCount"];
                    if (Count != null)
                    {
                        pageHelper.RecordCount = int.Parse(Count.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                if (sdr != null && !sdr.IsClosed)
                {
                    sdr.Close();
                }
            }
            return(entityList);
        }
Ejemplo n.º 21
0
 private string GetTableName(TableAttribute tableAttribute)
 {
     return(!string.IsNullOrWhiteSpace(tableAttribute?.Name) ? tableAttribute?.Name : _namingConvention.ConvertToDbName(_t.Name));
 }
            public override Collection<Attribute> GetAttributes()
            {
                Collection<Attribute> attributes = new Collection<Attribute>();

                var attribute = new TableAttribute(this.TableName, this.PartitionKey, this.RowKey);
                attribute.Filter = Filter;
                var take = this.Take;
                if (take.HasValue)
                {
                    attribute.Take = take.Value;
                }
                attributes.Add(attribute);

                string account = Context.GetMetadataValue<string>("connection");
                if (!string.IsNullOrEmpty(account))
                {
                    attributes.Add(new StorageAccountAttribute(account));
                }

                return attributes;
            }
Ejemplo n.º 23
0
 public EntityMapping()
 {
     this._tableAttr  = typeof(T).GetCustomAttributes(typeof(TableAttribute), true).GetValue(0) as TableAttribute;
     this._properties = typeof(T).GetProperties();
 }
Ejemplo n.º 24
0
 protected override string TableName(Type tEntityType)
 {
     return($"{TableAttribute.GetName(tEntityType).ToUpper()}");
 }
Ejemplo n.º 25
0
 public static string GetTableAttributeName(this Type type, out TableAttribute att)
 {
     att = type.GetCustomAttribute <TableAttribute>();
     return(att?.Name ?? type.Name);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// 获取TableName,并将其重新赋值
 /// </summary>
 protected void ReSetTableName()
 {
     _dbContext.TableName = TableAttribute.GetName(typeof(TEntity));
 }
Ejemplo n.º 27
0
    private string GetMappedTableName(Type tParam)
    {
        TableAttribute tableAttribute = (TableAttribute)tParam.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault();

        return(tableAttribute.Name);
    }
Ejemplo n.º 28
0
        /// <summary>
        /// 得到保存实体对象的SQL,既可以插入也可以更新,主要用于事务中
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public String GetSaveEntitySQL(T entity)
        {
            string sql = string.Empty;

            if (entity == null)
            {
                return(sql);
            }

            object[] tableAttributeArray = typeof(T).GetCustomAttributes(typeof(TableAttribute), false);
            if (tableAttributeArray.Length == 0)  //该实体类无表名,则返回0
            {
                return(sql);
            }
            TableAttribute ta            = tableAttributeArray[0] as TableAttribute;
            string         tableName     = ta.TableName;
            string         primaryColumn = ta.PrimaryKeyColumn;

            StringBuilder sbInsert      = new StringBuilder();
            StringBuilder sbInsertParam = new StringBuilder();
            StringBuilder sbUpdate      = new StringBuilder();
            StringBuilder sbUpdateWhere = new StringBuilder();

            sbInsert.Append("insert into [" + tableName + "] (");
            sbInsertParam.Append(" values (");
            sbUpdate.Append("Update [" + tableName + "] \r\t set \r\t ");
            List <int> aa = new List <int>();

            PropertyInfo[]      propertyInfos = typeof(T).GetProperties();
            List <SqlParameter> sqlParamList  = new List <SqlParameter>();

            for (int i = 0; i < propertyInfos.Length; i++)
            {
                PropertyInfo    propInfo   = propertyInfos[i];
                ColumnAttribute columnAttr = GetColumnAttribute(propInfo);
                if (columnAttr == null)   //无列名,则不操作
                {
                    continue;
                }

                object propValue = propInfo.GetValue(entity, null);
                if (propValue == null)    //列值为null,只需修改UpdateSql
                {
                    sbUpdate.Append("[" + columnAttr.ColumnName + "] = NULL,");
                    continue;
                }

                if (columnAttr.ColumnName == primaryColumn)   //主键
                {
                    sql = "if not exists (select * from [" + tableName + "] where [" + primaryColumn + "]='" + propValue + "' ) \r\t begin \r\t";
                    sbUpdateWhere.Append(" Where [" + primaryColumn + "] = '" + propValue + "'");

                    if (columnAttr.IsIndentity)   //且是自增列,则不操作
                    {
                        continue;
                    }
                }

                sbInsert.Append("[" + columnAttr.ColumnName + "],");
                sbInsertParam.Append("'" + propValue + "',");

                sbUpdate.Append("[" + columnAttr.ColumnName + "] = '" + propValue + "',");
            }

            sql += sbInsert.Remove(sbInsert.Length - 1, 1).ToString() + ") " + sbInsertParam.Remove(sbInsertParam.Length - 1, 1).ToString() + ")" + " end \r\t else\r\t begin \r\t "
                   + sbUpdate.Remove(sbUpdate.Length - 1, 1) + sbUpdateWhere + " \r\t end;";

            return(sql);
        }
Ejemplo n.º 29
0
 protected static string GetTableName(TableAttribute tableAttr, Type MappedType)
 {
     return(((tableAttr != null && !string.IsNullOrEmpty(tableAttr.Name)) ? tableAttr.Name : MappedType.Name)?.ToUpper());
 }
Ejemplo n.º 30
0
        public override string GenerateQuery(Type type)
        {
            string tableName = TableAttribute.GetAttributeTable(type);

            StringBuilder queryBuilder = new StringBuilder($"CREATE TABLE IF NOT EXISTS `{tableName}` (");

            List <string> tableFields = new List <string>();
            List <string> primaryKeys = new List <string>();

            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                string propertyTypeName = property.PropertyType.Name;
                string propertyName     = property.Name;

                string sqlType = null;

                try
                {
                    sqlType = CSharpTypesToSqlTypesDictionary[propertyTypeName];
                }
                catch (Exception)
                {
                    throw new NotSupportedException("The C# type " + propertyTypeName + " is not supported for C# to SQL conversion.");
                }

                string dataType = sqlType;

                int?columnLength = ColumnLengthAttribute.GetAttributeColumnLength(property);
                if (columnLength != null || propertyTypeName == "String")
                {
                    dataType = string.Format(dataType, columnLength ?? 50);
                }

                bool isAutoIncrement = AutoIncrementAttribute.IsAutoIncrement(property);
                if (isAutoIncrement)
                {
                    if (Database.DatabaseDriver is MySQLoo)
                    {
                        dataType += " AUTO_INCREMENT";
                    }
                }

                bool isPrimaryKey = PrimaryKeyAttribute.IsPrimaryKey(property);
                if (isPrimaryKey)
                {
                    // Check if is SQLite/MySQL
                    if (Database.DatabaseDriver is MySQLoo)
                    {
                        primaryKeys.Add(propertyName);
                    }
                    else if (Database.DatabaseDriver is SQLite)
                    {
                        dataType += " PRIMARY KEY";
                    }
                }

                tableFields.Add($"{propertyName} {dataType}");
            }

            queryBuilder.Append(string.Join(", ", tableFields));
            if (primaryKeys.Count > 0)
            {
                queryBuilder.Append(", PRIMARY KEY (");
                queryBuilder.Append(string.Join(", ", primaryKeys));
                queryBuilder.Append(")");
            }

            queryBuilder.Append(");");

            return(queryBuilder.ToString());
        }
Ejemplo n.º 31
0
 internal TableExpression()
 {
     Attribute = new TableAttribute();
 }
Ejemplo n.º 32
0
        public static TableInfo GetTableInfo(object entity, DbOperateType dbOpType, PropertyInfo[] properties)
        {
            bool      breakForeach  = false;
            string    strPrimaryKey = string.Empty;
            TableInfo tableInfo     = new TableInfo();
            Type      type          = entity.GetType();

            TableAttribute tableAttr = GetTableAttribute(type, dbOpType);

            tableInfo.TableName      = tableAttr.Name;
            tableInfo.NoAutomaticKey = tableAttr.NoAutomaticKey;

            //tableInfo.TableName = GetTableName(type, dbOpType);

            if (dbOpType == DbOperateType.COUNT)
            {
                return(tableInfo);
            }

            foreach (PropertyInfo property in properties)
            {
                object propvalue  = null;
                string columnName = string.Empty;
                string propName   = columnName = property.Name;

                propvalue = ReflectionHelper.GetPropertyValue(entity, property);

                object[] propertyAttrs = property.GetCustomAttributes(false);
                for (int i = 0; i < propertyAttrs.Length; i++)
                {
                    object propertyAttr = propertyAttrs[i];
                    if (EntityHelper.IsCaseColumn(propertyAttr, dbOpType))
                    {
                        breakForeach = true; break;
                    }

                    string tempVal = GetColumnName(propertyAttr);
                    columnName = tempVal == string.Empty ? propName : tempVal;

                    if (propertyAttr is IdAttribute)
                    {
                        if (dbOpType == DbOperateType.INSERT || dbOpType == DbOperateType.DELETE)
                        {
                            IdAttribute idAttr = propertyAttr as IdAttribute;
                            tableInfo.Strategy = idAttr.Strategy;

                            if (CommonUtils.IsNullOrEmpty(propvalue))
                            {
                                strPrimaryKey = EntityHelper.GetPrimaryKey(propertyAttr, dbOpType);
                                if (!string.IsNullOrEmpty(strPrimaryKey))
                                {
                                    propvalue = strPrimaryKey;
                                }
                            }
                        }

                        tableInfo.Id.Key   = columnName;
                        tableInfo.Id.Value = propvalue;
                        tableInfo.PropToColumn.Put(propName, columnName);
                        tableInfo.ColumnToProp.Put(columnName, propName);
                        breakForeach = true;
                    }
                }

                if (breakForeach && dbOpType == DbOperateType.DELETE)
                {
                    break;
                }
                if (breakForeach)
                {
                    breakForeach = false; continue;
                }
                tableInfo.Columns.Put(columnName, propvalue);
                tableInfo.PropToColumn.Put(propName, columnName);
                tableInfo.ColumnToProp.Put(columnName, propName);
            }

            /*if (dbOpType == DbOperateType.UPDATE)
             * {
             *  tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);
             * }*/

            return(tableInfo);
        }
Ejemplo n.º 33
0
 public static void Ctor_String(string name)
 {
     TableAttribute attribute = new TableAttribute(name);
     Assert.Equal(name, attribute.Name);
     Assert.Null(attribute.Schema);
 }
Ejemplo n.º 34
0
        private SqlCommand DesignQuery(object value, PropertyInfo property, Dictionary <string, object> primaryKeys, TableAttribute tableAttribute)
        {
            var sqlCommand    = new SqlCommand();
            var stringBuilder = new StringBuilder();

            foreach (var primaryKey in primaryKeys)
            {
                sqlCommand.Parameters.AddWithValue($"@{primaryKey.Key}", primaryKey.Value);
                stringBuilder.Append($"{GetClause(primaryKey.Key,"<>")} and ");
            }

            if (!string.IsNullOrEmpty(this.UniqueQueryMethod))
            {
                var result = this.GetMethodResult <List <UniqueQuery> >(this.UniqueQueryMethod, value);
                if (result != null)
                {
                    foreach (var query in result)
                    {
                        stringBuilder.Append($"{GetClause(query.ColumnName, SqlQueryOperator(query.QueryOperator))} and ");
                        sqlCommand.Parameters.AddWithValue($"@{query.ColumnName}", query.Value);
                    }
                }
            }
            stringBuilder.Append(GetClause(property.Name, "="));
            sqlCommand.Parameters.AddWithValue($"@{property.Name}", property.GetValue(value));
            sqlCommand.CommandText = $"select {property.Name} from {tableAttribute.Schema}.{tableAttribute.Name} where {stringBuilder.ToString()}";
            return(sqlCommand);
        }
        public bool CreateIfNotExist() {
            var TableNames = new Dictionary<Type, TableAttribute>();
            var cnn = "";
            if (MembershipProvider != null) {
                if (MembershipProvider.GetType().GetGenericTypeDefinition() != typeof(EFMembershipProvider<,>))
                    throw new ArgumentException("INSTALL_Invalid_membership_provider_type".Resource());

                dynamic tablePrefix = ((dynamic)MembershipProvider).TablePrefix;
                dynamic tableSchema = ((dynamic)MembershipProvider).TableSchema;
                dynamic helper = ((dynamic)MembershipProvider).Helper;
                cnn = ((dynamic)MembershipProvider).ConnectionString;
                foreach (var item in (Dictionary<Type, TableAttribute>)helper.TableNames)
                    TableNames[item.Key] = item.Value;

                var propAppType = (PropertyInfo)helper.Get(Mapper.UserColumnType.Application);
                if (propAppType != null) {
                    var appType = propAppType.PropertyType;

                    var tblNameAttr = appType.GetCustomAttributes(typeof(TableAttribute), true);
                    var noPrefixAttr = appType.GetCustomAttributes(typeof(NoPrefixAttribute), true);

                    var ApplicationTableNoPrefix = noPrefixAttr != null && noPrefixAttr.Length > 0;
                    var first = tblNameAttr.FirstOrDefault() as TableAttribute;

                    TableAttribute ApplicationTableName;
                    if (first != null)
                        ApplicationTableName = first;
                    else
                        ApplicationTableName = new TableAttribute(appType.Name.Trim().Replace(" ", ""));
                    if (!string.IsNullOrEmpty(tableSchema)) ApplicationTableName.Schema = tableSchema;

                    if (!ApplicationTableNoPrefix && !string.IsNullOrWhiteSpace(tablePrefix)) {
                        var schema = ApplicationTableName.Schema;
                        ApplicationTableName = new TableAttribute(tablePrefix + ApplicationTableName.Name);
                        if (schema != null) ApplicationTableName.Schema = schema;
                    }

                    TableNames[appType] = ApplicationTableName;
                }
            }

            if (RoleProvider != null) {
                if (RoleProvider.GetType().GetGenericTypeDefinition() != typeof(EFRoleProvider<,,>))
                    throw new ArgumentException("INSTALL_Invalid_role_provider_type".Resource());

                dynamic tablePrefix = ((dynamic)RoleProvider).TablePrefix;
                dynamic tableSchema = ((dynamic)RoleProvider).TableSchema;
                dynamic helper1 = ((dynamic)RoleProvider).RoleHelper;
                if (string.IsNullOrEmpty(cnn))
                    cnn = ((dynamic)RoleProvider).ConnectionString;

                foreach (var item in (Dictionary<Type, TableAttribute>)helper1.TableNames)
                    TableNames[item.Key] = item.Value;

                dynamic helper2 = ((dynamic)RoleProvider).UserRoleHelper;
                foreach (var item in (Dictionary<Type, TableAttribute>)helper2.TableNames)
                    TableNames[item.Key] = item.Value;

                var propAppType = (PropertyInfo)helper1.Get(Mapper.RoleColumnType.Application);
                if (propAppType != null) {
                    var appType = propAppType.PropertyType;

                    var tblNameAttr = appType.GetCustomAttributes(typeof(TableAttribute), true);
                    var noPrefixAttr = appType.GetCustomAttributes(typeof(NoPrefixAttribute), true);

                    var ApplicationTableNoPrefix = noPrefixAttr != null && noPrefixAttr.Length > 0;
                    var first = tblNameAttr.FirstOrDefault() as TableAttribute;

                    TableAttribute ApplicationTableName;
                    if (first != null)
                        ApplicationTableName = first;
                    else
                        ApplicationTableName = new TableAttribute(appType.Name.Trim().Replace(" ", ""));
                    if (!string.IsNullOrEmpty(tableSchema)) ApplicationTableName.Schema = tableSchema;

                    if (!ApplicationTableNoPrefix && !string.IsNullOrWhiteSpace(tablePrefix)) {
                        var schema = ApplicationTableName.Schema;
                        ApplicationTableName = new TableAttribute(tablePrefix + ApplicationTableName.Name);
                        if (schema != null) ApplicationTableName.Schema = schema;
                    }

                    TableNames[appType] = ApplicationTableName;
                }
            }

            var internalContext = new InternalInstallDataContext(cnn);
            internalContext.TableNames = TableNames;
            return internalContext.Database.CreateIfNotExists();
        }
Ejemplo n.º 36
0
 private IMongoCollection <TEntity> GetCollectionEntity()
 {
     return(_MongoDatabase.GetCollection <TEntity>(TableAttribute.GetName(typeof(TEntity))));
 }
Ejemplo n.º 37
0
        private ITableEntity JObjectToTableEntityConverterFunc(JObject source, TableAttribute attribute)
        {
            var result = this.CreateTableEntityFromJObject(attribute.PartitionKey, attribute.RowKey, source);

            return(result);
        }
Ejemplo n.º 38
0
        public void ColumnMapping()
        {
            var table   = new TableAttribute("Lorem", "ipsum");
            var mapper  = new ColumnMapper(null);
            var columns = mapper.Map <EntityBase>(table);

            Assert.IsTrue(columns.All(c => c.TableName == "Lorem" && c.TableSchema == "ipsum"));

            var discriminator = columns[0];

            Assert.AreEqual(discriminator.ColumnName, ColumnMapper.DiscriminatorColumnName);
            Assert.AreEqual(discriminator.ColumnType, "nvarchar(255)");
            Assert.IsNull(discriminator.DeclaringTypes);
            Assert.IsNull(discriminator.PropertyName);

            /* EntityBase */
            var seqEntityBase = new List <Type> {
                typeof(EntityBase)
            };

            var id = columns[1];

            Assert.AreEqual(id.ColumnName, "Id");
            Assert.AreEqual(id.ColumnType, "int");
            Assert.IsTrue(id.DeclaringTypes.SequenceEqual(seqEntityBase));
            Assert.AreEqual(id.PropertyName, "Id");

            var entityId = columns[2];

            Assert.AreEqual(entityId.ColumnName, "EntityId");
            Assert.AreEqual(entityId.ColumnType, "uniqueidentifier");
            Assert.IsTrue(entityId.DeclaringTypes.SequenceEqual(seqEntityBase));
            Assert.AreEqual(entityId.PropertyName, "EntityId");

            var name = columns[3];

            Assert.AreEqual(name.ColumnName, "Name");
            Assert.AreEqual(name.ColumnType, "nvarchar(max)");
            Assert.IsTrue(name.DeclaringTypes.SequenceEqual(seqEntityBase));
            Assert.AreEqual(name.PropertyName, "Name");

            var date = columns[4];

            Assert.AreEqual(date.ColumnName, "Date");
            Assert.AreEqual(date.ColumnType, "datetime2");
            Assert.IsTrue(date.DeclaringTypes.SequenceEqual(seqEntityBase));
            Assert.AreEqual(date.PropertyName, "Date");

            /* Class A */
            var seqClassA = new List <Type> {
                typeof(ClassA)
            };
            var seqClassAB = new List <Type> {
                typeof(ClassA), typeof(ClassB)
            };

            var number1 = columns[5];

            Assert.AreEqual(number1.ColumnName, "NumberOfSomething");
            Assert.AreEqual(number1.ColumnType, "int");
            Assert.IsTrue(number1.DeclaringTypes.SequenceEqual(seqClassAB));
            Assert.AreEqual(number1.PropertyName, "NumberOfSomething");

            var createdOn = columns[6];

            Assert.AreEqual(createdOn.ColumnName, "CreatedOn");
            Assert.AreEqual(createdOn.ColumnType, "datetime2");
            Assert.IsTrue(createdOn.DeclaringTypes.SequenceEqual(seqClassA));
            Assert.AreEqual(createdOn.PropertyName, "CreatedOn");

            /* Class B */
            var seqClassBC = new List <Type> {
                typeof(ClassB), typeof(ClassC)
            };

            var text = columns[7];

            Assert.AreEqual(text.ColumnName, "Text");
            Assert.AreEqual(text.ColumnType, "nvarchar(max)");
            Assert.IsTrue(text.DeclaringTypes.SequenceEqual(seqClassBC));
            Assert.AreEqual(text.PropertyName, "Text");

            /* Class D */
            var seqClassD = new List <Type> {
                typeof(ClassD)
            };

            var number2 = columns[8];

            Assert.AreEqual(number2.ColumnName, "ClassDNumberOfSomething");
            Assert.AreEqual(number2.ColumnType, "bigint");
            Assert.IsTrue(number2.DeclaringTypes.SequenceEqual(seqClassD));
            Assert.AreEqual(number2.PropertyName, "NumberOfSomething");

            /* Class E */
            var seqClassE = new List <Type> {
                typeof(ClassE)
            };

            var lorem = columns[9];

            Assert.AreEqual(lorem.ColumnName, "Lorem");
            Assert.AreEqual(lorem.ColumnType, "nvarchar(max)");
            Assert.IsTrue(lorem.DeclaringTypes.SequenceEqual(seqClassE));
            Assert.AreEqual(lorem.PropertyName, "Lorem");

            Assert.AreEqual(columns.Count(), 10);
        }
Ejemplo n.º 39
0
 public static void Schema_Set_ReturnsExpected(string value)
 {
     TableAttribute attribute = new TableAttribute("Perspicacia Tick") { Schema = value };
     Assert.Equal(value, attribute.Schema);
 }