public void Update(TEntity entity)
        {
            var updatedEntity = context.Entry(entity);

            updatedEntity.State = EntityState.Modified;
            context.SaveChanges();
        }
        public void Add(TEntity entity)
        {
            var addedEntity = context.Entry(entity);

            addedEntity.State = EntityState.Added;
            context.SaveChanges();
        }
        public void Delete(TEntity entity)
        {
            var deletedEntity = context.Entry(entity);

            deletedEntity.State = EntityState.Deleted;
            context.SaveChanges();
        }
Пример #4
0
        public TEntity GetRandomPersonSeed <TEntity>() where TEntity : Person, new()
        {
            TEntity person = new TEntity();
            string  gender = _randomGenerator.GetRandomElement(genders);

            if (gender == "Female")
            {
                person.FirstName = _randomGenerator.GetRandomElement(femaleNames);
            }
            else
            {
                person.FirstName = _randomGenerator.GetRandomElement(maleNames);
            }
            person.LastName    = _randomGenerator.GetRandomElement(lastNames);
            person.Nationality = _randomGenerator.GetRandomElement(nationalites);
            person.Address     = _randomGenerator.GetRandomElement(addresses)
                                 + " " + _randomGenerator.GetRandomElement(streets);
            person.Gender      = gender;
            person.Height      = _randomGenerator.GetRandomInt(150, 230);
            person.Weight      = _randomGenerator.GetRandomInt(50, 130);
            person.DateOfBirth = _randomGenerator.GetRandomDate();
            person.Photo       = "URL";
            var criminal = person as Criminal;

            if (criminal != null)
            {
                criminal.Description = "Test description.";
            }
            return(person);
        }
Пример #5
0
        private DbTypeInfo GetDbTypeInfo <TEntity>()
            where TEntity : IDbEntity, new()
        {
            Type       entityType = typeof(TEntity);
            DbTypeInfo entityDbTypeInfo;

            if (!DbConnection.dbTypeInfo.TryGetValue(entityType, out entityDbTypeInfo))
            {
                IDbEntity        defaultEntity          = new TEntity();
                SchemaCollection entitySchemaCollection = new SchemaCollection();

                foreach (DbOperationInfo operation in defaultEntity.DbOperations.Values)
                {
                    if (operation.ParameterType != null && !entitySchemaCollection.Contains(operation.ParameterType))
                    {
                        DataTable schemaTable = this.GetSchema(operation.ParameterType);
                        entitySchemaCollection.Add(schemaTable);
                    }
                }

                entityDbTypeInfo = new DbTypeInfo()
                {
                    DefaultEntity = defaultEntity,
                    SchemaInfo    = entitySchemaCollection
                };

                DbConnection.dbTypeInfo[entityType] = entityDbTypeInfo;
            }

            return(entityDbTypeInfo);
        }
Пример #6
0
        /// <summary>
        /// 创建实体,创建完,注册
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public TEntity CreateEntity <TEntity>() where TEntity : IEntity
        {
            TEntity entity = Activator.CreateInstance <TEntity>();

            SubscribeEntity(entity);
            return(entity);
        }
Пример #7
0
            public static TFactory For(TEntity entity)
            {
                var factoryType = typeof(TFactory);

                var exceptionType = typeof(InvalidAggregateAccess <>).MakeGenericType(typeof(TAggregate));

                var constructorInfo   = factoryType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Single();
                var asexceptionMethod = exceptionType.GetMethod("AsException", new Type[0], new ParameterModifier[0]);

                // TODO: improve
                var parameters = constructorInfo.GetParameters().Skip(1);
                var list       = new List <object>()
                {
                    entity
                };

                foreach (var item in parameters)
                {
                    var returnType          = item.ParameterType;
                    var genericTypeArgument = returnType.GenericTypeArguments.First();
                    var exception           = Activator.CreateInstance(exceptionType, returnType.Name);
                    var ex = Expression.Throw(Expression.Call(Expression.Constant(exception, exceptionType), asexceptionMethod), genericTypeArgument);

                    var delegateType = typeof(Func <>).MakeGenericType(returnType);
                    var expression   = Expression.Lambda(returnType, ex).Compile();
                    list.Add(expression);
                }

                var res = constructorInfo.Invoke(list.ToArray());

                return(res as TFactory);
            }
Пример #8
0
            public TEntity Get(Func <TEntity> valFactory)
            {
                TEntity tmpEntity = default(TEntity);

                System.Threading.Interlocked.Exchange(ref tmpEntity, valFactory());
                return(tmpEntity);
            }
Пример #9
0
        /// <summary>
        /// 返回单个实体
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public TEntity ToFirst <TEntity>()
        {
            TEntity t = default(TEntity);

            using (IDataReader reader = ToDataReader())
            {
                //var tempt = EntityUtils.Mapper.Map<TEntity>(reader);
                //if (tempt.Any())
                //{
                //    t = tempt.First();
                //}
                var result = EntityUtils.ReaderToEnumerable <TEntity>(reader).ToArray();
                if (result.Any())
                {
                    t = result.First();
                }
                #region 2015-08-10注释
                //if (reader.Read())
                //{
                //    t = DataUtils.Create<TEntity>();
                //    t.SetPropertyValues(reader);
                //}
                #endregion
            }
            return(t);
        }
Пример #10
0
        // PUT: api/{controller}/Post/5
        /// <summary>
        /// Post via PUT.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public IHttpActionResult Put(int id, [FromBody] TEntity item)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != item.Id)
            {
                return(BadRequest());
            }

            _context.Entry(item).State = EntityState.Modified;

            try
            {
                _context.SaveChanges();
            }
            catch (DbUpdateConcurrencyException dcx)
            {
                if (!Exists(id))
                {
                    return(NotFound());
                }

                Audit.Log.Error(AppConstants.ErrorMessages.DbUpdateConcurrencyExceptionMessage, dcx);

                throw;
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #11
0
        internal static Mock <IEntityStateEntry> CreateMockStateEntry <TEntity>() where TEntity : class, new()
        {
            var mockStateEntry = new Mock <IEntityStateEntry>();
            var fakeEntity     = new TEntity();

            mockStateEntry.Setup(e => e.Entity).Returns(fakeEntity);

            var entitySet = new EntitySet("foo set", "foo schema", "foo table", "foo query", new EntityType("E", "N", DataSpace.CSpace));

            entitySet.ChangeEntityContainerWithoutCollectionFixup(new EntityContainer("foo container", DataSpace.CSpace));
            mockStateEntry.Setup(e => e.EntitySet).Returns(entitySet);

            mockStateEntry.Setup(e => e.EntityKey).Returns(
                new EntityKey(
                    "foo.bar",
                    new[] { new KeyValuePair <string, object>("foo", "bar") }));

            var modifiedProps = new List <string>
            {
                "Foo",
                "ValueTypeProp",
                "Bar"
            };

            mockStateEntry.Setup(e => e.GetModifiedProperties()).Returns(modifiedProps);
            mockStateEntry.Setup(e => e.SetModifiedProperty(It.IsAny <string>())).Callback <string>(modifiedProps.Add);

            return(mockStateEntry);
        }
Пример #12
0
        public TEntity CreateEntity <TEntity>() where TEntity : class, new()
        {
            var enity = new TEntity();

            _dbContext.Set <TEntity>().Add(enity);
            return(enity);
        }
Пример #13
0
        public TEntity ShallowClone <TEntity>() where TEntity : BaseEntity, new()
        {
            var clonedEntity = new TEntity();

            foreach (var propertyInfo in GetType().GetProperties()
                     .Where(p => p.GetCustomAttributes(true).OfType <JsonPropertyAttribute>().Any()))
            {
                if (propertyInfo.IsCollectionOf <BaseEntity>())
                {
                    continue;
                }
                if (!propertyInfo.PropertyType.IsValueType)
                {
                    continue;
                }
                if (!propertyInfo.CanRead || !propertyInfo.CanWrite)
                {
                    continue;
                }

                clonedEntity.SetProperty(propertyInfo.Name, GetProperty(propertyInfo.Name));
            }

            return(clonedEntity);
        }
        /// <summary>
        /// 初始化类型
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        void IDataTrigger.InitType <TEntity>()
        {
            if (TypeInterfaces.TryGetValue(typeof(TEntity), out var type))
            {
                return;
            }
            var entity = new TEntity();

            type = 0;
            if (entity is IAuthorData)
            {
                type |= TypeofIAuthorData;
            }
            if (entity is IHistoryData)
            {
                type |= TypeofIHistoryData;
            }
            if (entity is IOrganizationData)
            {
                type |= TypeofIOrganizationData;
            }
            if (entity is IVersionData)
            {
                type |= TypeofIVersionData;
            }
            TypeInterfaces.Add(typeof(TEntity), type);
        }
Пример #15
0
        ITEntity IStorageService.AddEntity(string sFname, string sMname, string sMother, string sLname, string sDOB, int jAge, string sEmail1, string sContact1, string sHouse,
                                           string sLocality, string sAddressLine, string sTaluka, string sDistrict, string sState, string sIdProof, string sIdProofPath, int jType, bool bcommit)
        {
            TEntity tEntity = new TEntity()
            {
                sFname       = sFname,
                sMname       = sMname,
                sMother      = sMother,
                sLname       = sLname,
                sDOB         = sDOB,
                jAge         = jAge,
                sEmail1      = sEmail1,
                sContact1    = sContact1,
                sHouse       = sHouse,
                sLocality    = sLocality,
                sAddressLine = sAddressLine,
                sTaluka      = sTaluka,
                sDistrict    = sDistrict,
                sState       = sState,
                sIdProof     = sIdProof,
                sIdProofPath = sIdProofPath,
                jType        = jType,
                bStatus      = true,
                dStamp       = DateTime.UtcNow
            };

            _Sb.TEntities.InsertOnSubmit(tEntity);
            if (bcommit)
            {
                CommitToDB();
            }
            return(new OTEntity(tEntity));
        }
Пример #16
0
        ITEntity IStorageService.UpdateEntity(ITEntity iEntity, string sFname, string sMname, string sMother, string sLname, string sDOB, int jAge, string sEmail1, string sContact1, string sHouse, string sLocality, string sAddressLine, string sTaluka, string sDistrict, string sState, string sIdProof, string sIdProofPath, bool bcommit)

        {
            TEntity tEntity = (iEntity as OTEntity)._oMoniker;

            tEntity.sFname       = sFname;
            tEntity.sMname       = sMname;
            tEntity.sMother      = sMother;
            tEntity.sLname       = sLname;
            tEntity.sDOB         = sDOB;
            tEntity.sState       = sState;
            tEntity.jAge         = jAge;
            tEntity.sEmail1      = sEmail1;
            tEntity.sContact1    = sContact1;
            tEntity.sHouse       = sHouse;
            tEntity.sLocality    = sLocality;
            tEntity.sAddressLine = sAddressLine;
            tEntity.sTaluka      = sTaluka;
            tEntity.sDistrict    = sDistrict;
            tEntity.sIdProof     = sIdProof;
            tEntity.sIdProofPath = sIdProofPath;
            tEntity.dStamp       = DateTime.UtcNow;
            if (bcommit)
            {
                CommitToDB();
            }
            return(new OTEntity(tEntity));
        }
Пример #17
0
        public virtual List <TEntity> GetEntities <TEntity>()
            where TEntity : class, IDbEntity
        {
            if (!typeof(TEntity).Equals(Type))
            {
                throw new ArgumentException("The generic type must match the type of the data bundle.");
            }

            List <TEntity> entities = new List <TEntity>();

            if (Contains <List <TEntity> >(EntitiesParameterKey))
            {
                entities = GetParameter <List <TEntity> >(EntitiesParameterKey);
            }

            if (entities.Count == 0)
            {
                TEntity entity = GetEntity <TEntity>();
                if (entity != null)
                {
                    entities.Add(entity);
                }
            }
            return(entities);
        }
Пример #18
0
        /// <summary>
        /// Executes the query and returns the entity of the first row in the result set returned by the query. All other columns and rows are ignored.
        /// </summary>
        /// <typeparam name="TEntity">Entity type.</typeparam>
        /// <returns>Entity instance.</returns>
        public TEntity ExecuteEntity <TEntity>() where TEntity : class, new()
        {
            TEntity result = default(TEntity);

            Database db = this._databaseProvider.Value.CreateDatabase(this.databaseConfig.ConnectionString, this.databaseConfig.Type);

            if (db != null)
            {
                DbCommand command = this.GetRealCommand(db);
                if (command != null)
                {
                    try
                    {
                        using (IDataReader reader = db.ExecuteReader(command))
                        {
                            if (reader.Read())
                            {
                                result = EntityBuilder.BuildEntity <TEntity>(reader);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        command.Parameters.Clear();
                    }
                }
            }

            return(result);
        }
Пример #19
0
        public TEntity CreateEntity <TEntity>() where TEntity : EntityBase, new()
        {
            var enity = new TEntity();

            DbContext.Set <TEntity>().Add(enity);
            return(enity);
        }
Пример #20
0
        public virtual IDictionary <string, TEntity> GetAllItems <TEntity>() where TEntity : DataStoreLib.Models.TableEntity
        {
            Debug.Assert(_table != null);

            var operationList = new Dictionary <string, TableResult>();

            TableQuery <MovieEntity> query = new TableQuery <MovieEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "CloudMovie"));

            // execute query
            IEnumerable <MovieEntity> movieResults = _table.ExecuteQuery <MovieEntity>(query);

            var returnDict = new Dictionary <string, TEntity>();
            int iter       = 0;

            foreach (var tableResult in movieResults)
            {
                TEntity entity = null;

                entity = tableResult as TEntity;

                returnDict.Add(tableResult.MovieId, entity);
                iter++;
            }

            return(returnDict);
        }
Пример #21
0
        /// <summary>
        /// 初始化类型
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        public static void InitType <TEntity>() where TEntity : class, new()
        {
            if (TypeInterfaces.ContainsKey(typeof(TEntity)))
            {
                return;
            }
            var entity = new TEntity();
            int type   = 0;

            if (entity is IAuthorData)
            {
                type |= TypeofIAuthorData;
            }
            if (entity is IHistoryData)
            {
                type |= TypeofIHistoryData;
            }
            if (entity is IOrganizationData)
            {
                type |= TypeofIOrganizationData;
            }
            if (entity is IDepartmentData)
            {
                type |= TypeofIDepartmentData;
            }
            if (entity is IVersionData)
            {
                type |= TypeofIVersionData;
            }
            TypeInterfaces.Add(typeof(TEntity), type);
        }
        private TEntity createRecord <TEntity>() where TEntity : new()
        {
            TEntity record;

            record = new TEntity();
            //try to auto map the header names to properties on the class
            //first get all of the property infos for the type:
            AutoGeneratePropertyMappings <TEntity>();

            foreach (var pm in _propertyMappings)
            {
                int index = pm.MappedColumnIndex;
                if (pm.UseColumnName && FirstRowIsHeader)
                {
                    index = Array.FindIndex(FieldHeaders, t => t.Equals(pm.MappedColumnName, StringComparison.InvariantCultureIgnoreCase));
                    if (index == -1)
                    {
                        if (!IgnoreMappingExceptions)
                        {
                            //string message = string.Format("Mapping exception occurred.  The property '{0}' could not be mapped to column '{1}'", pm.PropertyInfo.Name, pm.MappedColumnName);
                            throw new DelimitedTextReaderMappingException(pm.PropertyInfo.Name, pm.MappedColumnName);
                        }
                        index = pm.MappedColumnIndex;
                    }
                }
                //var value = Convert.ChangeType(CurrentRecord[index], pm.PropertyInfo.PropertyType);
                if (pm.GetTypeConverter() != null)
                {
                    var value = pm.GetTypeConverter().ConvertFromString(CurrentRecord[index]);
                    pm.PropertyInfo.SetValue(record, value);
                }
            }

            return(record);
        }
Пример #23
0
 public Change(TEntity entity, long id, object[] original, ChangeType changeType)
 {
     Entity     = entity;
     Id         = id;
     Original   = original;
     ChangeType = changeType;
 }
Пример #24
0
        /// <summary>
        /// 获取实体的列特性
        /// </summary>
        /// <returns></returns>
        public List <EntityPropColumnAttributes> GetEntityColumnAtrributes <TEntity>() where TEntity : new()
        {
            List <EntityPropColumnAttributes> list = new List <EntityPropColumnAttributes>();
            TEntity model = new TEntity();

            foreach (PropertyInfo prop in model.GetType().GetProperties())
            {
                EntityPropColumnAttributes entity = new EntityPropColumnAttributes();
                entity.propName     = prop.Name;
                entity.fieldName    = prop.Name;
                entity.isPrimaryKey = false;
                entity.isIdentity   = false;
                Type type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                entity.typeName = type.FullName;
                object[] CustomAttributesArr = prop.GetCustomAttributes(typeof(ColumnAttribute), false);
                if (CustomAttributesArr.Count() > 0)
                {
                    foreach (var obj in CustomAttributesArr)
                    {
                        ColumnAttribute attr = obj as ColumnAttribute;
                        entity.fieldName    = attr.Name;
                        entity.isPrimaryKey = attr.IsPrimaryKey;
                        entity.isIdentity   = attr.IsDbGenerated;
                    }
                }
            }
            return(list);
        }
Пример #25
0
        public static TEntity[] FindAll <TEntity>() where TEntity : new()
        {
            return(With.Transaction <TEntity[]>(delegate(IDbCommand command)
            {
                Mapping mapping = GetMappingFor(typeof(TEntity));
                command.CommandText = GenerateSelect <TEntity>();
                using (IDataReader reader = command.ExecuteReader())
                {
                    List <TEntity> entities = new List <TEntity>();
                    while (reader.Read())
                    {
                        TEntity entity = new TEntity();
                        object value = reader.GetValue(reader.GetOrdinal(mapping.PrimaryKey.Key));

                        mapping.PrimaryKey.Value.SetValue(entity,
                                                          Convert.ChangeType(value, mapping.PrimaryKey.Value.PropertyType), null);

                        foreach (KeyValuePair <string, PropertyInfo> kvp in mapping.Columns)
                        {
                            value = reader.GetValue(reader.GetOrdinal(kvp.Key));
                            if (value == DBNull.Value)
                            {
                                value = null;
                            }

                            kvp.Value.SetValue(entity,
                                               Convert.ChangeType(value, kvp.Value.PropertyType), null);
                        }

                        entities.Add(entity);
                    }
                    return entities.ToArray();
                }
            }));
        }
Пример #26
0
        protected TEntity BuildSampleEntity <TEntity>() where TEntity : ObjectBase, new()
        {
            TEntity entity = new TEntity();

            PropertyInfo[] properties = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            foreach (PropertyInfo property in properties)
            {
                if (property.GetSetMethod() != null)
                {
                    object value;

                    Type propertyType = property.PropertyType;

                    if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        value = GetRandomValue(Nullable.GetUnderlyingType(propertyType));
                    }
                    else
                    {
                        value = GetRandomValue(propertyType);
                    }

                    property.SetValue(entity, value);
                }
            }
            return(entity);
        }
        public TEntity Add(TEntity entity)
        {
            this.dbContext.Set <TEntity>().Add(entity);
            this.dbContext.SaveChanges();

            return(entity);
        }
Пример #28
0
        public TEntity CreateEntity <TEntity>() where TEntity : class, IEntity, new()
        {
            var entity = new TEntity();

            RegisterEntity(entity);
            return(entity);
        }
Пример #29
0
 public Change(TEntity entity, object[] key, object[] original, ChangeType changeType)
 {
     Entity     = entity;
     Key        = key;
     Original   = original;
     ChangeType = changeType;
 }
Пример #30
0
        /// <summary>
        /// Exec a storeprocedure with returl db table map value
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="sqltext"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static IEnumerable <TEntity> GetEntity <TEntity>() //where TEntity : class
        {
            Type myType = typeof(TEntity);
            var  prop   = myType.GetProperties();

            IEnumerable <TEntity> result = null;

            using (var conn = new OracleConnection())
            {
                conn.ConnectionString = ConnectionString;
                conn.Open();
                using (var command = conn.CreateCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = "SELECT * FROM TB_SN_SO_WT_HIST WHERE SO_TRANSFER_FLAG = 'N' AND rownum <= 100";

                    var reader = command.ExecuteReader();
                    if (typeof(TEntity).IsClass)
                    //result = AutoMapper.Mapper.DynamicMap<IDataReader, IEnumerable<TEntity>>(reader);
                    {
                        List <TEntity> lst = new List <TEntity>();
                        while (reader.Read())
                        {
                            var entity = (TEntity)Activator.CreateInstance(myType);
                            foreach (var inf in prop)
                            {
                                object value = reader[inf.Name];
                                if (value == System.DBNull.Value)
                                {
                                    continue;
                                }
                                inf.SetValue(entity, value, null);
                            }
                            lst.Add(entity);
                        }
                        if (lst.Count != 0)
                        {
                            result = lst;
                        }
                    }
                    else
                    {
                        List <TEntity> lst = new List <TEntity>();
                        while (reader.Read())
                        {
                            // get the results of each column
                            TEntity item = (TEntity)reader[0];
                            lst.Add(item);
                        }
                        if (lst.Count != 0)
                        {
                            result = lst;
                        }
                    }
                }
                conn.Close();
            }
            return(result);
        }
Пример #31
0
 public UpdateStp(string name, StoredProcedureParameters parameters, string table, TableColumns columns, string keyName, string keyColumn, string keyType, TEntity entity)
     : base(name, parameters, table, columns, keyName, keyColumn, keyType)
 {
     Entity = entity;
 }