Esempio n. 1
0
        /// <summary>
        /// 从数据库读取  必须有Key特性
        /// </summary>
        /// <param name="dataEntity">数据实体</param>
        public static bool Read <T>(this IDataEntity <T> dataEntity) where T : DbContext, new()
        {
            var    context    = dataEntity.GetDbContext();
            var    properties = dataEntity.GetType().GetProperties();
            var    result     = false;
            object model      = null;

            foreach (var item in properties)
            {
                if (item.GetCustomAttribute(typeof(KeyAttribute)) != null)
                {
                    var keyValue = item.GetValue(dataEntity);
                    model = context.Set(dataEntity.GetType()).Find(keyValue);
                    break;
                }
            }
            if (model != null)
            {
                result = true;
                foreach (var item in properties)
                {
                    item.SetValue(dataEntity, item.GetValue(model));
                }
            }
            return(result);
        }
Esempio n. 2
0
        private long _Add(IDataEntity item)
        {
            var set = _context.Set(_type);

            IDataEntity newItem;

            if ((typeof(IDeletable).IsAssignableFrom(item.GetType())))
            {
                var delItem = (IDeletable)item;
                delItem.IsDeleted = false;
            }

            if (TrackChanges)
            {
                var trackItem = (ITrackable)item;
                trackItem.DateCreated = DateTime.Now;
                if (User != null)
                {
                    trackItem.CreatedBy     = User.Id;
                    trackItem.CreatedByUser = User;
                }
                newItem = (IDataEntity)set.Add(trackItem);
            }
            else
            {
                newItem = (IDataEntity)set.Add(item);
            }
            return(newItem.Id);
        }
Esempio n. 3
0
        public static IDataEntity FixNavigationProperties(DataRepositoryProperties props, IDataEntity item)
        {
            if (item != null && props != null)
            {
                Type           type       = item.GetType();
                PropertyInfo[] properties = type.GetProperties();

                foreach (
                    PropertyInfo property in
                    properties.Where(p => typeof(IEnumerable <IDataEntity>).IsAssignableFrom(p.PropertyType))
                    .ToArray())
                {
                    var propType = property.PropertyType;

                    var propCol = (property.GetValue(item) as IEnumerable <IDataEntity>).ToArray();

                    if (!propCol.IsNullOrEmpty())
                    {
                        propCol = _GetItems(props, propCol).ToArray();

                        var containedType = propType.GenericTypeArguments.First();
                        var newList       = _CreateList(containedType, propCol);
                        newList.Append(propCol);
                        //var newCol = _GetItem(props, propCol).Select(i =>(typeof(int))i);
                        property.SetValue(item, newList);
                    }
                }

                return(item);
            }
            return(null);
        }
Esempio n. 4
0
        /// <summary>
        /// 更新数据实体值到数据库
        ///备注: 根据当前数据对象的值向数据库插入一条数据库记录。如果没有为对象添加任何属性,则不会产生任何效果。
        /// </summary>
        /// <param name="dataEntity">数据实体</param>
        public static void Update <T>(this IDataEntity <T> dataEntity) where T : DbContext, new()
        {
            var context = dataEntity.GetDbContext();

            context.Set(dataEntity.GetType()).Attach(dataEntity);
            context.Entry(dataEntity).State = EntityState.Modified;
            context.SaveChanges();
        }
Esempio n. 5
0
 /// <summary>
 /// 实体值复制、连同子对象和引用对象一并复制。
 /// </summary>
 /// <param name="dataEntity">源实体</param>
 /// <param name="target">目标实体</param>
 private static void CopyTo(this IDataEntity dataEntity, IDataEntity target)
 {
     //需要判断两个类是否相同
     if (dataEntity.GetType().FullName != target.GetType().FullName)
     {
         throw new Exception("类型不一致");
     }
     else
     {
         throw new Exception("未实现");
     }
 }
Esempio n. 6
0
        /// <summary>
        /// 判断数据实体是否在数据库中存在 必须有Key特性
        /// </summary>
        /// <param name="dataEntity">数据实体</param>
        public static bool ExistsInDb <T>(this IDataEntity <T> dataEntity) where T : DbContext, new()
        {
            var context    = dataEntity.GetDbContext();
            var properties = dataEntity.GetType().GetProperties();

            foreach (var item in properties)
            {
                if (item.GetCustomAttribute(typeof(KeyAttribute)) != null)
                {
                    var keyValue = item.GetValue(dataEntity);
                    var model    = context.Set(dataEntity.GetType()).Find(keyValue);
                    if (model == null)
                    {
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                }
            }
            throw new Exception("未找到实体类主键");
        }
Esempio n. 7
0
        public IEnumerable <IDataEntity> GetAll(string type)
        {
            IDataEntity dataEntity = DataEntityFactory.GetDataEntity(type);

            var dataEntityType = dataEntity.GetType();

            foreach (var property in dataEntityType.GetProperties())
            {
                if (property.Name == "type")
                {
                    continue;
                }

                property.GetType();
            }

            _manager.GetConnection(_config);
            _manager.Disconnect();

            return(null);
        }
Esempio n. 8
0
        /// <summary>
        /// Updates the record.
        ///   If there is a property marked as EntityKey the update will consider that field as Unique Key
        ///  If there is not any property marked as EntityKey the function will throw an exception
        /// </summary>
        /// <param name="record">The record.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">
        /// There is not any property marked as EntityKey
        /// or
        /// A Class marked with attribute NotInsert cannot perform write opperations
        /// </exception>
        public bool UpdateRecord(IDataEntity record)
        {
            List <PropertyInfo>         properties  = record.GetType().GetProperties().ToList();
            Dictionary <string, string> FieldsNames = new Dictionary <string, string>();

            var customAttributes = record.GetType().GetCustomAttributes();

            OnBeforeInsert(null);
            //find if there is an EntityKey property. If there is not we abort the operation

            Boolean KeyExists = false;

            foreach (PropertyInfo property in properties)
            {
                DataInterface.Attribbutes.EntityKey KeyProperty = (DataInterface.Attribbutes.EntityKey)(from attr in property.GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.EntityKey) select attr).FirstOrDefault();
                if (KeyProperty != null)
                {
                    KeyExists = true;
                    break;
                }
            }

            if (KeyExists == false)
            {
                throw new Exception("There is not any property marked as EntityKey");
            }


            DataInterface.Attribbutes.NotInsert NotInsertAttribute = (DataInterface.Attribbutes.NotInsert)(from attr in record.GetType().GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.NotInsert) select attr).FirstOrDefault();

            if (NotInsertAttribute != null)
            {
                throw new Exception("A Class marked with attribute NotInsert cannot perform write opperations");
            }


            //first find the table attribute to obtain the maped db table
            DataInterface.Attribbutes.Table TableAttribute = (DataInterface.Attribbutes.Table)(from attr in record.GetType().GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.Table) select attr).FirstOrDefault();

            using (SqlConnection connection = new SqlConnection(this.Source))
            {
                connection.Open();
                try
                {
                    StringBuilder Query = new StringBuilder();
                    if (TableAttribute != null)
                    {
                        Query.Append($"Update {TableAttribute.Name} set ");
                    }
                    else
                    {
                        Query.Append($"Update  {record.GetType().Name} set");
                    }

                    //get the properties of the entity

                    // create the insert query

                    CreateUpdateQuery(record, Query, properties, FieldsNames);

                    var com = new SqlCommand(Query.ToString(), connection);
                    //Create the sql parameters
                    if (_Encryptor != null)
                    {
                        if (record is IEncryptableClass)
                        {
                            _Encryptor.EncryptProperties((IEncryptableClass)record);
                        }
                    }
                    SetInsetParameters(record, properties, FieldsNames, com);

                    foreach (PropertyInfo property in properties)
                    {
                        DataInterface.Attribbutes.EntityKey KeyProperty = (DataInterface.Attribbutes.EntityKey)(from attr in property.GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.EntityKey) select attr).FirstOrDefault();
                        if (KeyProperty != null)
                        {
                            DataInterface.Attribbutes.Field FieldProperty = (DataInterface.Attribbutes.Field)(from attr in property.GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.Field) select attr).FirstOrDefault();
                            if (FieldProperty != null)
                            {
                                com.Parameters.AddWithValue($"@{FieldProperty.Name}", property.GetValue(record));
                            }
                            else
                            {
                                com.Parameters.AddWithValue($"@{property.Name}", property.GetValue(record));
                            }
                        }
                    }

                    com.ExecuteNonQuery();
                    //find the Key property of the entity

                    if (_Encryptor != null)
                    {
                        if (record is IEncryptableClass)
                        {
                            _Encryptor.Decryptproperties((IEncryptableClass)record);
                        }
                    }
                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (connection.State == System.Data.ConnectionState.Open)
                    {
                        connection.Close();
                    }
                    throw;
                }
            }
            return(true);
        }
Esempio n. 9
0
        /// <summary>
        /// Adds the record asynchronous.
        /// If there is not a "Field" attribute on a property then the property is maped to the datasource
        /// with it's name.
        /// If a property is marked as EntityKey then the property will take the Identity value after the insert
        /// If there is a Table attribute on the Entity then the entity is mapped to the specified Datasource table otherwise is mapped with it's name.
        /// If an encryptor instance is available the properties marked as MuStEncrypt are encrypted before insert and decrypted after the insert
        /// </summary>
        /// <param name="Record">The record.</param>
        /// <returns></returns>
        public async Task <bool> AddRecord_Async(IDataEntity Record)
        {
            OnBeforeInsert(new OperatorEventArguments()
            {
                Data = Record
            });


            DataInterface.Attribbutes.NotInsert NotInsertAttribute = (DataInterface.Attribbutes.NotInsert)(from attr in Record.GetType().GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.NotInsert) select attr).FirstOrDefault();

            if (NotInsertAttribute != null)
            {
                throw new Exception("A Class marked with attribute NotInsert cannot perform write opperations");
            }


            //first find the table attribute to obtain the maped db table
            DataInterface.Attribbutes.Table TableAttribute = (DataInterface.Attribbutes.Table)(from attr in Record.GetType().GetCustomAttributes(true) where attr.GetType() == typeof(DataInterface.Attribbutes.Table) select attr).FirstOrDefault();

            using (SqlConnection connection = new SqlConnection(this.Source))
            {
                connection.Open();
                try
                {
                    StringBuilder Query = new StringBuilder();
                    if (TableAttribute != null)
                    {
                        Query.Append($"Insert INTO {TableAttribute.Name} (");
                    }
                    else
                    {
                        Query.Append($"Insert INTO {Record.GetType ().Name} (");
                    }


                    //get the properties of the entity
                    List <PropertyInfo>         properties  = Record.GetType().GetProperties().ToList();
                    Dictionary <string, string> FieldsNames = new Dictionary <string, string>();
                    List <string> FieldsHolders             = new List <string>();
                    // create the insert query
                    CreateInsertQuery(Record, Query, properties, FieldsNames);
                    var com = new SqlCommand(Query.ToString(), connection);
                    //Create the sql parameters
                    if (_Encryptor != null)
                    {
                        if (Record is IEncryptableClass)
                        {
                            _Encryptor.EncryptProperties((IEncryptableClass)Record);
                        }
                    }

                    SetInsetParameters(Record, properties, FieldsNames, com);

                    int result = Convert.ToInt32(await com.ExecuteScalarAsync());
                    //find the Key property of the entity
                    UpdateKeyPropery(Record, properties, result);

                    if (_Encryptor != null)
                    {
                        if (Record is IEncryptableClass)
                        {
                            _Encryptor.Decryptproperties((IEncryptableClass)Record);
                        }
                    }
                    connection.Close();
                }
                catch (Exception ex)
                {
                    if (connection.State == System.Data.ConnectionState.Open)
                    {
                        connection.Close();
                    }
                    OnRecordInsertFailed(new OperatorEventArguments()
                    {
                        Data = Record
                    });
                    return(false);
                }
            }
            OnRecordInserted(new OperatorEventArguments()
            {
                Data = Record
            });
            return(true);
        }