예제 #1
0
        public virtual T CreateDataAccessObject <T, K>(K primaryKey, PrimaryKeyType primaryKeyType)
            where T : DataAccessObject
        {
            var objectPropertyAndValues = this.GetObjectPropertyValues <K>(typeof(T), primaryKey, primaryKeyType);

            if (objectPropertyAndValues.Any(keyValue => keyValue.Value == null))
            {
                throw new MissingOrInvalidPrimaryKeyException();
            }

            var existing = this.GetCurrentDataContext(false).GetObject(this.GetConcreteTypeFromDefinitionType(typeof(T)), objectPropertyAndValues);

            if (existing != null)
            {
                T obj = null;

                ActionUtils.IgnoreExceptions(() => obj = this.GetReference <T, K>(primaryKey, primaryKeyType));

                throw new ObjectAlreadyExistsException(obj, null, "CreateDataAccessObject");
            }
            else
            {
                var retval = this.RuntimeDataAccessModelInfo.CreateDataAccessObject <T>(this, true);

                retval.ToObjectInternal().SetPrimaryKeys(objectPropertyAndValues);
                retval.ToObjectInternal().FinishedInitializing();
                retval.ToObjectInternal().SubmitToCache();

                return(retval);
            }
        }
예제 #2
0
        private void mapAttributeInformation(String propertyName, Attribute annotation)
        {
            if (typeof(Column).IsAssignableFrom(annotation.GetType()))
            {
                if (((Column)annotation).fetch == FetchType.EAGER)
                {
                    fetchTypes.Add(propertyName, FetchType.EAGER);
                }

                if (annotation.GetType() == typeof(OneToMany))
                {
                    OneToMany oneToManyAtt = (OneToMany)annotation;

                    oneToMany.Add(propertyName, oneToManyAtt.pkName + "@" +
                                  oneToManyAtt.tableName + "@" + oneToManyAtt.fkName);
                    return;
                }
            }

            if (annotation.GetType() == typeof(Id))
            {
                Id idAtt = (Id)annotation;

                idName         = propertyName;
                primaryKeyType = idAtt.type;
            }

            mappings.Add(propertyName, ((MappingAttribute)annotation).name);
        }
예제 #3
0
        /// <summary>
        /// 生成唯一主建
        /// </summary>
        /// <param name="keyType">主建类型</param>
        /// <param name="keyLen">主建长度</param>
        /// <returns></returns>
        public static string MakePrimaryKey(PrimaryKeyType keyType, PrimaryKeyLen keyLen)
        {
            var primaryKey = string.Empty;

            lock (locker)
            {
                switch (keyType)
                {
                case PrimaryKeyType.Other:
                    if (keyLen == PrimaryKeyLen.V4)
                    {
                        primaryKey = GetGuidString();
                    }
                    else
                    {
                        primaryKey = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0).ToString();
                    }
                    break;

                default:
                    if (keyLen == PrimaryKeyLen.V1)
                    {
                        primaryKey = GetKeyString(keyType);
                    }
                    else
                    {
                        primaryKey = GetKeyString(keyType, (int)keyLen);
                    }
                    break;
                }
            }
            return(primaryKey);
        }
예제 #4
0
 /// <summary>
 /// 创建key字符串 10位
 /// </summary>
 /// <param name="keyType">主建类型</param>
 /// <returns></returns>
 private static string GetKeyString(PrimaryKeyType keyType)
 {
     try
     {
         int keyLen     = 10;
         var primaryKey = string.Empty;
         lock (locker)
         {
             var k = BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0);
             if (k < 0)
             {
                 k = -k;
             }
             primaryKey = (int)keyType + k.ToString();
             while (primaryKey.Length < keyLen)
             {
                 primaryKey += new Random(k).Next();
             }
             primaryKey = primaryKey.Substring(0, keyLen);
         }
         return(primaryKey);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
예제 #5
0
        /// <summary>
        /// 根据主键类型转换为编码字符串
        /// </summary>
        /// <param name="pkType">主键类型</param>
        /// <returns>编码字符串</returns>
        public static string ToCodeString(this PrimaryKeyType pkType)
        {
            switch (pkType)
            {
            case PrimaryKeyType.INT:

                return("int");

            case PrimaryKeyType.STRING:

                return("string");

            case PrimaryKeyType.GUID:

                return("Guid");

            case PrimaryKeyType.SNOWFLAKE:

                return("long");

            default:

                return(null);
            }
        }
예제 #6
0
 /// <summary>
 /// Initialises a new instance of TableAttribute with the specified table name, primary key property and the primary key type.
 /// </summary>
 /// <param name="tableName">The name of the table in the system which holds the data for the attributed class.</param>
 /// <param name="primaryKey">The name of the property in the attributed class which provides a unique identifier for this class.</param>
 /// <param name="keyType">The type of primary key used to identify unique instances of this class.</param>
 public TableAttribute(string tableName, string primaryKey, PrimaryKeyType keyType)
 {
     this.tableName  = tableName;
     this.primaryKey = primaryKey;
     this.keyType    = keyType;
     defaultOrder    = String.Empty;
 }
예제 #7
0
        public virtual T GetReference <T, K>(K primaryKey, PrimaryKeyType primaryKeyType = PrimaryKeyType.Auto)
            where T : DataAccessObject
        {
            var propertyValues = this.GetObjectPropertyValues <K>(typeof(T), primaryKey, primaryKeyType);

            return(this.GetReference <T>(propertyValues));
        }
예제 #8
0
 private void AddKeyMapping(PrimaryKeyType type, string columnName, string propertyName)
 {
     AddMapping(columnName, propertyName);
     KeyType       = type;
     KeyGeneration = PrimaryKeyGeneration.None;
     KeyColumn     = columnName;
     KeyProperty   = propertyName;
 }
예제 #9
0
        public override bool Equals(object obj)
        {
            TypeFk compareTo = obj as TypeFk;

            if (compareTo != null)
            {
                return(PrimaryKeyType.Equals(compareTo.PrimaryKeyType) && ForeignKeyType.Equals(compareTo.ForeignKeyType));
            }
            return(base.Equals(obj));
        }
예제 #10
0
        public virtual IQueryable <T> GetQueryableByPrimaryKey <K>(K primaryKey, PrimaryKeyType primaryKeyType = PrimaryKeyType.Auto)
        {
            if (this.idType == null)
            {
                throw new NotSupportedException($"Type {this.typeDescriptor.PersistedName} does not define any primary keys");
            }

            if (typeof(K) == this.idType && !this.idType.IsDataAccessObjectType())
            {
                if (this.typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new ArgumentException("Composite primary key expected", nameof(primaryKey));
                }

                var parameterExpression = Expression.Parameter(typeof(T), "value");
                var body      = Expression.Equal(Expression.Property(parameterExpression, this.primaryKeyProperty), Expression.Constant(primaryKey));
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
            else if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeof(K)))
            {
                if (this.typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new ArgumentException("Composite primary key expected", nameof(primaryKey));
                }

                var parameterExpression = Expression.Parameter(typeof(T), "value");
                var body      = Expression.Equal(Expression.Property(parameterExpression, this.primaryKeyProperty), Expression.Constant(Convert.ChangeType(primaryKey, this.idType)));
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
            else
            {
                var deflated            = this.DataAccessModel.GetReference <T, K>(primaryKey, primaryKeyType);
                var parameterExpression = Expression.Parameter(typeof(T), "value");
                var body      = Expression.Equal(parameterExpression, Expression.Constant(deflated));
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
        }
예제 #11
0
        public virtual IQueryable <T> GetQueryableByPrimaryKey <K>(K primaryKey, PrimaryKeyType primaryKeyType = PrimaryKeyType.Auto)
        {
            if (typeof(K) == IdType)
            {
                if (this.typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new ArgumentException("Composite primary key expected", "primaryKey");
                }

                var parameterExpression = Expression.Parameter(typeof(T), "value");
                var body = Expression.Equal(Expression.Property(parameterExpression, PrimaryKeyInfoCache <T> .IdPropertyInfo), Expression.Constant(primaryKey));

                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
            else if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeof(K)))
            {
                if (this.typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new ArgumentException("Composite primary key expected", "primaryKey");
                }

                var parameterExpression = Expression.Parameter(typeof(T), "value");
                var body = Expression.Equal(Expression.Property(parameterExpression, PrimaryKeyInfoCache <T> .IdPropertyInfo), Expression.Constant(Convert.ChangeType(primaryKey, IdType)));

                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
            else
            {
                var deflated            = this.DataAccessModel.GetReference <T, K>(primaryKey, primaryKeyType);
                var parameterExpression = Expression.Parameter(typeof(T), "value");
                var body = Expression.Equal(parameterExpression, Expression.Constant(deflated));

                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
        }
예제 #12
0
        public virtual IQueryable <T> GetManyByPrimaryKey <K>(IEnumerable <K> primaryKeys, PrimaryKeyType primaryKeyType)
        {
            if (this.idType == null)
            {
                throw new NotSupportedException($"Type {this.typeDescriptor.PersistedName} does not define any primary keys");
            }

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

            if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeof(K)) || (typeof(K) == this.idType && primaryKeyType != PrimaryKeyType.Composite))
            {
                if (!TypeDescriptor.IsSimpleType(this.idType))
                {
                    throw new ArgumentException($"Type {typeof(K)} needs to be convertable to {this.idType}", nameof(primaryKeys));
                }

                if (this.typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new ArgumentException("Composite primary key type expected", nameof(primaryKeys));
                }
            }

            if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeof(K)) || (typeof(K) == this.idType && primaryKeyType != PrimaryKeyType.Composite))
            {
                var propertyInfo        = this.primaryKeyProperty;
                var parameterExpression = Expression.Parameter(propertyInfo.PropertyType);
                var body      = Expression.Call(MethodInfoFastRef.EnumerableContainsMethod.MakeGenericMethod(propertyInfo.PropertyType), Expression.Constant(primaryKeyType), Expression.Property(parameterExpression, propertyInfo));
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
            else
            {
                var parameterExpression = Expression.Parameter(typeof(T));

                var deflatedObjects = primaryKeys
                                      .Select(c => this.DataAccessModel.GetReference <T, K>(c, primaryKeyType))
                                      .ToArray();

                var body      = Expression.Call(PrimaryKeyInfoCache <T> .EnumerableContainsMethod, Expression.Constant(deflatedObjects), parameterExpression);
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
        }
예제 #13
0
 public virtual IQueryable <T> GetManyByPrimaryKey <K>(K[] primaryKeys, PrimaryKeyType primaryKeyType)
 {
     return(this.GetManyByPrimaryKey((IEnumerable <K>)primaryKeys, primaryKeyType));
 }
예제 #14
0
        protected internal ObjectPropertyValue[] GetObjectPropertyValues <K>(Type type, K primaryKey, PrimaryKeyType primaryKeyType = PrimaryKeyType.Auto)
        {
            if (primaryKey == null)
            {
                throw new ArgumentNullException(nameof(primaryKey));
            }

            var key = new Pair <RuntimeTypeHandle, RuntimeTypeHandle>(type.TypeHandle, Type.GetTypeHandle(primaryKey));

            if (!this.objectPropertyValuesByAnonymousKeyFuncByType.TryGetValue(key, out var func))
            {
                var isSimpleKey      = false;
                var typeOfPrimaryKey = primaryKey.GetType();
                var typeDescriptor   = this.TypeDescriptorProvider.GetTypeDescriptor(type);
                var idPropertyType   = typeDescriptor.PrimaryKeyProperties[0].PropertyType;

                if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeOfPrimaryKey) || (typeDescriptor.PrimaryKeyCount == 1 && idPropertyType.IsAssignableFrom(typeOfPrimaryKey) && primaryKeyType == PrimaryKeyType.Auto))
                {
                    isSimpleKey = true;
                }

                if (isSimpleKey && typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new InvalidOperationException($"Composite primary key expected for type {type} instead of key of type {typeOfPrimaryKey}");
                }

                var parameter      = Expression.Parameter(typeof(object));
                var constructor    = ConstructorInfoFastRef.ObjectPropertyValueConstructor;
                var typedParameter = Expression.Convert(parameter, typeOfPrimaryKey);

                var initializers = new List <Expression>();
                var replacementPrimaryKeyValues = new Dictionary <string, Expression>();

                if (typeDescriptor.PrimaryKeyDerivableProperties.Count > 0)
                {
                    var properties = typeDescriptor
                                     .PrimaryKeyDerivableProperties
                                     .Where(c => typeOfPrimaryKey.GetMostDerivedProperty(c.PropertyName) != null)
                                     .ToList();

                    replacementPrimaryKeyValues = properties.ToDictionary
                                                  (
                        c => c.ComputedMemberAssignTarget.Name,
                        c => SqlMemberAccessReplacer.Replace
                        (
                            c.ComputedMemberAssignmentValue,
                            c.PropertyInfo,
                            Expression.Convert(Expression.Property(typedParameter, typedParameter.Type.GetMostDerivedProperty(c.PropertyName)), c.PropertyInfo.PropertyType)
                        )
                                                  );
                }

                foreach (var property in typeDescriptor.PrimaryKeyProperties)
                {
                    var isObjectType = property.PropertyType.IsDataAccessObjectType();

                    Expression valueExpression;

                    if (isSimpleKey)
                    {
                        valueExpression = parameter;
                    }
                    else
                    {
                        if (!replacementPrimaryKeyValues.TryGetValue(property.PropertyName, out valueExpression))
                        {
                            valueExpression = Expression.Property(typedParameter, typedParameter.Type.GetMostDerivedProperty(property.PropertyName));
                        }
                    }

                    Expression primaryKeyValue;

                    var propertyInfo = DataAccessObjectTypeBuilder.GetPropertyInfo(GetConcreteTypeFromDefinitionType(typeDescriptor.Type), property.PropertyName);

                    if (isObjectType)
                    {
                        var method = MethodInfoFastRef.DataAccessModelGetReferenceMethod.MakeGenericMethod(propertyInfo.PropertyType, valueExpression.Type);

                        if (isSimpleKey || valueExpression.Type.IsDataAccessObjectType())
                        {
                            primaryKeyValue = valueExpression;
                        }
                        else
                        {
                            primaryKeyValue = Expression.Call(Expression.Constant(this), method, valueExpression, Expression.Constant(PrimaryKeyType.Composite));
                        }
                    }
                    else
                    {
                        primaryKeyValue = Expression.Call(MethodInfoFastRef.ConvertChangeTypeMethod, Expression.Convert(valueExpression, typeof(object)), Expression.Constant(propertyInfo.PropertyType));
                    }

                    var newExpression = Expression.New
                                        (
                        constructor,
                        Expression.Constant(propertyInfo.PropertyType),
                        Expression.Constant(property.PropertyName),
                        Expression.Constant(property.PersistedName),
                        Expression.Constant(property.PropertyName.GetHashCode()),
                        Expression.Convert(primaryKeyValue, typeof(object))
                                        );

                    initializers.Add(newExpression);
                }

                var body = Expression.NewArrayInit(typeof(ObjectPropertyValue), initializers);

                var lambdaExpression = Expression.Lambda(typeof(Func <object, ObjectPropertyValue[]>), body, parameter);

                func = (Func <object, ObjectPropertyValue[]>)lambdaExpression.Compile();

                this.objectPropertyValuesByAnonymousKeyFuncByType = this.objectPropertyValuesByAnonymousKeyFuncByType.Clone(key, func);
            }

            return(func(primaryKey));
        }
예제 #15
0
 public virtual T GetReference <T>(object primaryKey, PrimaryKeyType primaryKeyType = PrimaryKeyType.Auto)
     where T : DataAccessObject
 {
     return((T)GetReference(typeof(T), GetObjectPropertyValues(typeof(T), primaryKey, primaryKeyType)));
 }
예제 #16
0
 /// <summary>
 /// 生成唯一主建
 /// </summary>
 /// <param name="keyType">主建类型</param>
 /// <returns></returns>
 public static string MakePrimaryKey(PrimaryKeyType keyType)
 {
     return(MakePrimaryKey(keyType, PrimaryKeyLen.V2));
 }
예제 #17
0
        public List <T> ExcelToList <T>(List <string> properties, string filePath, string sheetName, bool isFirstRowColumn, string primaryKey, PrimaryKeyType pkType, int startKey)
        {
            List <T> retList = ReadToList <T>(properties, filePath, sheetName, isFirstRowColumn, primaryKey, pkType, startKey);

            return(retList);
        }
예제 #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PrimaryKeyAttribute"/> class.
 /// </summary>
 /// <param name="generator">The generator.</param>
 /// <param name="column">The column.</param>
 public PrimaryKeyAttribute(PrimaryKeyType generator, string column)
 {
     Generator = generator;
     Column    = column;
 }
예제 #19
0
 public PrimaryKeyAttribute(PrimaryKeyType generator)
 {
     _generator = generator;
 }
예제 #20
0
		/// <summary>
		/// Initializes a new instance of the <see cref="PrimaryKeyAttribute"/> class.
		/// </summary>
		/// <param name="generator">The generator.</param>
		public PrimaryKeyAttribute(PrimaryKeyType generator)
		{
			this.generator = generator;
		}
예제 #21
0
        protected internal ObjectPropertyValue[] GetObjectPropertyValues <K>(Type type, K primaryKey, PrimaryKeyType primaryKeyType = PrimaryKeyType.Auto)
        {
            if (Equals(primaryKey, default(K)) && typeof(K).IsClass)
            {
                throw new ArgumentNullException(nameof(primaryKey));
            }

            var idType = primaryKey.GetType();
            var primaryKeyTypeHandle = Type.GetTypeHandle(primaryKey);
            Func <object, ObjectPropertyValue[]> func;

            if (!this.propertyInfoAndValueGetterFuncByType.TryGetValue(primaryKeyTypeHandle, out func))
            {
                var isSimpleKey      = false;
                var typeOfPrimaryKey = Type.GetTypeFromHandle(primaryKeyTypeHandle);
                var typeDescriptor   = this.TypeDescriptorProvider.GetTypeDescriptor(type);
                var idPropertyType   = typeDescriptor.PrimaryKeyProperties[0].PropertyType;

                if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(idType) || (idPropertyType.IsAssignableFrom(idType) && primaryKeyType == PrimaryKeyType.Auto))
                {
                    isSimpleKey = true;
                }

                if (isSimpleKey && typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new InvalidOperationException("Composite primary key expected");
                }

                var parameter      = Expression.Parameter(typeof(object));
                var constructor    = ConstructorInfoFastRef.ObjectPropertyValueConstructor;
                var typedParameter = Expression.Convert(parameter, typeOfPrimaryKey);

                var initializers = new List <Expression>();
                var replacementPrimaryKeyValues = new Dictionary <string, Expression>();

                if (typeDescriptor.PrimaryKeyDerivableProperties.Count > 0)
                {
                    var properties = typeDescriptor
                                     .PrimaryKeyDerivableProperties
                                     .Where(c => idType.GetProperty(c.PropertyName, BindingFlags.Instance | BindingFlags.Public) != null)
                                     .ToList();

                    replacementPrimaryKeyValues = properties.ToDictionary
                                                  (
                        c => c.ComputedMemberAssignTarget.Name,
                        c => MemberAccessReplacer.Replace
                        (
                            c.ComputedMemberAssignmentValue, c.PropertyInfo,
                            Expression.Property(typedParameter, c.PropertyName)
                        )
                                                  );
                }

                foreach (var property in typeDescriptor.PrimaryKeyProperties)
                {
                    var isObjectType = property.PropertyType.IsDataAccessObjectType();

                    Expression valueExpression;

                    if (isSimpleKey)
                    {
                        valueExpression = parameter;
                    }
                    else
                    {
                        if (!replacementPrimaryKeyValues.TryGetValue(property.PropertyName, out valueExpression))
                        {
                            valueExpression = Expression.PropertyOrField(typedParameter, property.PropertyName);
                        }
                    }

                    Expression primaryKeyValue;

                    var propertyInfo = DataAccessObjectTypeBuilder.GetPropertyInfo(this.GetConcreteTypeFromDefinitionType(typeDescriptor.Type), property.PropertyName);

                    if (isObjectType)
                    {
                        var method = MethodInfoFastRef.DataAccessModelGetReferenceMethod.MakeGenericMethod(propertyInfo.PropertyType, valueExpression.Type);

                        if (isSimpleKey || valueExpression.Type.IsDataAccessObjectType())
                        {
                            primaryKeyValue = valueExpression;
                        }
                        else
                        {
                            primaryKeyValue = Expression.Call(Expression.Constant(this), method, valueExpression, Expression.Constant(PrimaryKeyType.Composite));
                        }
                    }
                    else
                    {
                        primaryKeyValue = Expression.Call(MethodInfoFastRef.ConvertChangeTypeMethod, Expression.Convert(valueExpression, typeof(object)), Expression.Constant(propertyInfo.PropertyType));
                    }

                    var newExpression = Expression.New
                                        (
                        constructor,
                        Expression.Constant(propertyInfo.PropertyType),
                        Expression.Constant(property.PropertyName),
                        Expression.Constant(property.PersistedName),
                        Expression.Constant(property.PropertyName.GetHashCode()),
                        Expression.Convert(primaryKeyValue, typeof(object))
                                        );

                    initializers.Add(newExpression);
                }

                var body = Expression.NewArrayInit(typeof(ObjectPropertyValue), initializers);

                var lambdaExpression = Expression.Lambda(typeof(Func <object, ObjectPropertyValue[]>), body, parameter);

                func = (Func <object, ObjectPropertyValue[]>)lambdaExpression.Compile();

                var newPropertyInfoAndValueGetterFuncByType = new Dictionary <RuntimeTypeHandle, Func <object, ObjectPropertyValue[]> >(this.propertyInfoAndValueGetterFuncByType)
                {
                    [primaryKeyTypeHandle] = func
                };

                this.propertyInfoAndValueGetterFuncByType = newPropertyInfoAndValueGetterFuncByType;
            }

            return(func(primaryKey));
        }
예제 #22
0
        protected internal virtual DataAccessObject GetReference <K>(Type type, K primaryKey, PrimaryKeyType primaryKeyType)
        {
            var primaryKeyValues = this.GetObjectPropertyValues(type, primaryKey, primaryKeyType);

            return(this.GetReference(type, primaryKeyValues));
        }
예제 #23
0
        /// <summary>
        /// 将excel中的数据导入到泛型List中
        /// </summary>
        /// <param name="filePath">文件保存的绝对路径,包含文件名</param>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否为表头</param>
        /// <returns>返回的List</returns>
        private List <T> ReadToList <T>(List <string> properties, string filePath, string sheetName, bool isFirstRowColumn, string primaryKey = "", PrimaryKeyType pkType = PrimaryKeyType.无, int startKey = -1)
        {
            _workbook = null;
            ISheet   sheet    = null;
            List <T> list     = new List <T>();
            int      startRow = -1;

            if (pkType == PrimaryKeyType.数字 && startKey == -1)
            {
                return(null);
            }

            try
            {
                _fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                if (filePath.IndexOf(".xlsx") > 0) // 2007版本
                {
                    _workbook = new XSSFWorkbook(_fs);
                }
                else if (filePath.IndexOf(".xls") > 0) // 2003版本
                {
                    _workbook = new HSSFWorkbook(_fs);
                }
                if (_workbook == null)
                {
                    return(null);
                }
                if (sheetName != null)
                {
                    sheet = _workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = _workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = _workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow  = sheet.GetRow(0);
                    int  cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;

                    //查询第一列不合并的行
                    for (int i = 0; i <= rowCount; ++i)
                    {
                        IRow startRw = sheet.GetRow(i);
                        if (startRw != null)
                        {
                            for (int j = startRw.FirstCellNum; j < cellCount; ++j)
                            {
                                ICell cell = startRw.GetCell(j);

                                if (cell != null)
                                {
                                    string cellValue = cell.StringCellValue;
                                    if (cell.IsMergedCell)
                                    {
                                        if (j + 1 < cellCount)
                                        {
                                            ICell cellAdd = startRw.GetCell(j + 1);
                                            if (cellAdd.StringCellValue == "")
                                            {
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (cellValue == "")
                                        {
                                            break;
                                        }
                                    }

                                    if (j + 1 == cellCount)
                                    {
                                        startRow = i;
                                        break;
                                    }
                                }
                            }
                        }

                        if (startRow >= 0)
                        {
                            break;
                        }
                    }

                    int col = 0;
                    //取得数据
                    for (int i = startRow + 1; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;              //没有数据的行默认是null       
                        }
                        T s = System.Activator.CreateInstance <T>();
                        //属性赋值
                        if (pkType == PrimaryKeyType.无)
                        {
                            foreach (var item in properties)
                            {
                                if (row.GetCell(col) != null) //没有数据的单元格都默认是null
                                {
                                    typeof(T).GetProperty(item).SetValue(s, row.GetCell(col), null);
                                }
                                ++col;
                            }
                        }
                        else
                        {
                            foreach (var item in properties)
                            {
                                if (row.GetCell(col) != null) //没有数据的单元格都默认是null
                                {
                                    PropertyInfo pi = typeof(T).GetProperty(item);
                                    if (item.Equals(primaryKey))
                                    {
                                        if (pkType == PrimaryKeyType.数字)
                                        {
                                            pi.SetValue(s, startKey, null);
                                            startKey++;
                                        }
                                        else
                                        {
                                            pi.SetValue(s, Guid.NewGuid(), null);
                                        }
                                    }
                                    else
                                    {
                                        pi.SetValue(s, row.GetCell(col), null);
                                    }
                                }
                                ++col;
                            }
                        }
                        list.Add(s);
                    }
                }
                return(list);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return(null);
            }
        }
예제 #24
0
 public virtual T Create <K>(K primaryKey, PrimaryKeyType primaryKeyType)
 {
     return(this.DataAccessModel.CreateDataAccessObject <T, K>(primaryKey, primaryKeyType));
 }
예제 #25
0
 public virtual T GetByPrimaryKey <K>(K primaryKey, PrimaryKeyType primaryKeyType)
 {
     return(GetQueryableByPrimaryKey(primaryKey, primaryKeyType).Single());
 }
예제 #26
0
 public virtual T GetByPrimaryKeyOrDefault <K>(K primaryKey, PrimaryKeyType primaryKeyType)
 {
     return(this.GetQueryableByPrimaryKey(primaryKey, primaryKeyType).SingleOrDefault());
 }
예제 #27
0
 public PrimaryKeyAttribute(PrimaryKeyType generator, String column) : this(generator)
 {
     _column = column;
 }
예제 #28
0
 public bool Is(PrimaryKeyType type)
 {
     return(Type == type);
 }
예제 #29
0
        public virtual IDataAccessObjectAdvanced CreateDataAccessObject <K>(Type type, K primaryKey, PrimaryKeyType primaryKeyType)
        {
            if (!typeof(IDataAccessObjectAdvanced).IsAssignableFrom(type) ||
                !typeof(DataAccessObject <>).IsAssignableFromIgnoreGenericParameters(type))
            {
                throw new ArgumentException("Type must be a DataAccessObjectType", nameof(type));
            }

            var objectPropertyAndValues = this.GetObjectPropertyValues(type, primaryKey, primaryKeyType);

            if (objectPropertyAndValues.Any(keyValue => keyValue.Value == null))
            {
                throw new MissingOrInvalidPrimaryKeyException();
            }

            var existing = this.GetCurrentDataContext(false).GetObject(this.GetConcreteTypeFromDefinitionType(type), objectPropertyAndValues);

            if (existing != null)
            {
                IDataAccessObjectAdvanced obj = null;

                ActionUtils.IgnoreExceptions(() => obj = this.GetReference(type, primaryKey, primaryKeyType));

                throw new ObjectAlreadyExistsException(obj, null, "CreateDataAccessObject");
            }
            else
            {
                var retval = this.RuntimeDataAccessModelInfo.CreateDataAccessObject(type, this, true);

                retval.ToObjectInternal().SetPrimaryKeys(objectPropertyAndValues);
                retval.ToObjectInternal().FinishedInitializing();
                retval.ToObjectInternal().SubmitToCache();

                return(retval);
            }
        }
예제 #30
0
		/// <summary>
		/// Initializes a new instance of the <see cref="PrimaryKeyAttribute"/> class.
		/// </summary>
		/// <param name="generator">The generator.</param>
		/// <param name="column">The PK column.</param>
		public PrimaryKeyAttribute(PrimaryKeyType generator, String column) : this(generator)
		{
			this.column = column;
		}
예제 #31
0
        public virtual IQueryable <T> GetManyByPrimaryKey <K>(IEnumerable <K> primaryKeys, PrimaryKeyType primaryKeyType)
        {
            if (primaryKeys == null)
            {
                throw new ArgumentNullException("primaryKeys");
            }

            if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeof(K)) || (typeof(K) == IdType && primaryKeyType != PrimaryKeyType.Composite))
            {
                if (!TypeDescriptor.IsSimpleType(IdType))
                {
                    throw new ArgumentException(string.Format("Type {0} needs to be convertable to {1}", typeof(K), IdType), "primaryKeys");
                }

                if (this.typeDescriptor.PrimaryKeyCount != 1)
                {
                    throw new ArgumentException("Composite primary key type expected", "primaryKeys");
                }
            }

            if (primaryKeyType == PrimaryKeyType.Single || TypeDescriptor.IsSimpleType(typeof(K)) || (typeof(K) == IdType && primaryKeyType != PrimaryKeyType.Composite))
            {
                var propertyInfo        = PrimaryKeyInfoCache <T> .IdPropertyInfo;
                var parameterExpression = Expression.Parameter(propertyInfo.PropertyType, "value");

                var body      = Expression.Call(null, MethodInfoFastRef.EnumerableContainsMethod.MakeGenericMethod(propertyInfo.PropertyType), Expression.Constant(primaryKeyType), Expression.Property(parameterExpression, propertyInfo));
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
            else
            {
                var parameterExpression = Expression.Parameter(typeof(T), "value");

                var deflatedObjects = primaryKeys
                                      .Select(c => this.DataAccessModel.GetReference <T, K>(c, primaryKeyType))
                                      .ToArray();

                var body      = Expression.Call(null, PrimaryKeyInfoCache <T> .EnumerableContainsMethod, Expression.Constant(deflatedObjects), parameterExpression);
                var condition = Expression.Lambda <Func <T, bool> >(body, parameterExpression);

                return(this.Where(condition));
            }
        }
예제 #32
0
 public virtual T GetReference <K>(K primaryKey, PrimaryKeyType primaryKeyType)
 {
     return(this.DataAccessModel.GetReference <T, K>(primaryKey, primaryKeyType));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PrimaryKeyAttribute"/> class.
 /// </summary>
 /// <param name="generator">The generator.</param>
 /// <param name="column">The column.</param>
 public PrimaryKeyAttribute(PrimaryKeyType generator, string column)
 {
     Generator = generator;
     Column = column;
 }