Exemplo n.º 1
0
 /// <summary>
 /// 批量删除
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="entities"></param>
 /// <returns></returns>
 public int Delete <T>(List <T> entities) where T : class
 {
     foreach (var entity in entities)
     {
         Dbcontext.Set <T>().Attach(entity);
         Dbcontext.Set <T>().Remove(entity);
     }
     return(DbTransaction == null?this.Commit() : 0);
 }
Exemplo n.º 2
0
        /// <summary>
        /// 根据条件更新
        /// </summary>
        /// <param name="modelModifyProps">要修改的列及修改后列的值集合</param>
        /// <param name="where">修改的条件</param>
        /// <returns>返回受影响行数</returns>
        public int Update <T>(T modelModifyProps, Expression <Func <T, bool> > where) where T : class, new()
        {
            int req = -1;

            //获取符合条件的数据
            List <T> list = Dbcontext.Set <T>().Where(where).ToList();

            Type t = typeof(T);
            //得到实体类属性值
            List <PropertyInfo> propertyInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
            //实体-属性集合字典
            Dictionary <string, PropertyInfo> dictionaryProps = new Dictionary <string, PropertyInfo>();

            //获取实体字段不为空的字段名
            string[] paramModifyStrings = new string[propertyInfos.Count];
            for (int i = 0; i < propertyInfos.Count; i++)
            {
                if (propertyInfos[i].GetValue(modelModifyProps, null) != null)
                {
                    paramModifyStrings[i] = propertyInfos[i].Name;
                }
            }

            //将实体属性重要修改属性,添加到集合中 Key-属性名 Value-属性对象
            propertyInfos.ForEach(p =>
            {
                if (paramModifyStrings.Contains(p.Name))
                {
                    dictionaryProps.Add(p.Name, p);
                }
            });

            //循环要修改的属性名
            foreach (string paramModifyString in paramModifyStrings)
            {
                //判断要修改的属性名是否在实体类的属性集合中
                if (!string.IsNullOrWhiteSpace(paramModifyString) && dictionaryProps.ContainsKey(paramModifyString))
                {
                    //如果存在则去除要修改属性对象
                    PropertyInfo info = dictionaryProps[paramModifyString];
                    //取出要修改的值
                    object newValue = info.GetValue(modelModifyProps, null);
                    //批量设置要修改的对象的属性
                    foreach (T n in list)
                    {
                        //为要修改的对象的要修改的属性设置新的值
                        info.SetValue(n, newValue, null);
                    }
                }
            }

            //req = dbcontext.SaveChanges();
            req = DbTransaction == null?this.Commit() : 0;

            return(req);
        }
Exemplo n.º 3
0
#pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type
		private List<T> Form_records<T>(
			string opt_sql=null,//иногда нужно задать свой sql
			DateTime startDate=default(DateTime), DateTime endDate = default(DateTime))
			where T:class
#pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type
		{
			string sql_cmd = Generate_sql_string(opt_sql??ReportName.Eng, 
				//если даты не указаны, что иногда нужно, то берём из стандартного источника
				startDate == default(DateTime)?ReportDates.StartDate:startDate,
				endDate == default(DateTime)?ReportDates.EndDate:endDate,
				Dbcontext, placeId, IsByDay, tesYear: ReportDates.TesYear, sku: SelectedSortOfProduction);
			return  Dbcontext.Set<T>().FromSql(sql_cmd).ToList();// генерируем sql строку для вывода данных для отчета
		}
Exemplo n.º 4
0
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="orderField">排序字段,多个用英文逗号隔开,类似:Id Asc,Name Desc</param>
        /// <param name="isAsc">是否升序</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="pageIndex">索引</param>
        /// <param name="total">总记录数</param>
        /// <returns></returns>
        public IEnumerable <T> FindList <T>(string orderField, bool isAsc, int pageSize, int pageIndex, out int total) where T : class, new()
        {
            string[]             order     = !string.IsNullOrEmpty(orderField) ? orderField.Split(',') : new[] { "" };
            MethodCallExpression resultExp = null;
            var tempData = Dbcontext.Set <T>().AsQueryable();

            try
            {
                if (!string.IsNullOrEmpty(order[0]))
                {
                    foreach (string item in order)
                    {
                        string orderPart = item;
                        orderPart = Regex.Replace(orderPart, @"\s+", " ");
                        string[] orderArry = orderPart.Split(' ');

                        bool sort = isAsc;
                        if (orderArry.Length == 2)
                        {
                            sort = orderArry[1].ToUpper() == "ASC" ? true : false;
                        }
                        var parameter = Expression.Parameter(typeof(T), "t");
                        var property  = typeof(T).GetProperty(orderArry[0]);
                        if (property != null)
                        {
                            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
                            var orderByExp     = Expression.Lambda(propertyAccess, parameter);
                            resultExp = Expression.Call(typeof(Queryable), sort ? "OrderBy" : "OrderByDescending", new Type[] { typeof(T), property.PropertyType }, tempData.Expression, Expression.Quote(orderByExp));
                        }
                    }
                }
                if (resultExp != null)
                {
                    tempData = tempData.Provider.CreateQuery <T>(resultExp);
                }
                tempData = tempData.Skip <T>(pageSize * (pageIndex - 1)).Take <T>(pageSize).AsQueryable();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            total = tempData.Count();
            return(tempData.ToList());
        }
Exemplo n.º 5
0
        /// <summary>
        ///更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update <T>(T entity) where T : class
        {
            Dbcontext.Set <T>().Attach(entity);
            Hashtable props = ConvertExtension.GetPropertyInfo <T>(entity);

            foreach (string item in props.Keys)
            {
                if (item != "PK")
                {
                    object value = Dbcontext.Entry(entity).Property(item).CurrentValue;
                    if (value != null)
                    {
                        if (value.ToString() == "&nbsp;")
                        {
                            Dbcontext.Entry(entity).Property(item).CurrentValue = null;
                        }
                        Dbcontext.Entry(entity).Property(item).IsModified = true;
                    }
                }
            }
            return(DbTransaction == null?this.Commit() : 0);
        }
Exemplo n.º 6
0
 public EUser GetUser(string username, string password)
 {
     return(Dbcontext.Set <EUser>().SingleOrDefault(p => p.Username == username && p.Password == password));
 }
Exemplo n.º 7
0
 public IEnumerable <EBook> GetByUserId(int userId)
 {
     return(Dbcontext.Set <EBook>().Where(t => t.UserId == userId).Select(t => t));
 }
Exemplo n.º 8
0
 /// <summary>
 /// 根据条件查询出一个集合
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="condition"></param>
 /// <returns></returns>
 public IEnumerable <T> FindList <T>(Expression <Func <T, bool> > condition) where T : class, new()
 {
     return(Dbcontext.Set <T>().Where(condition).ToList());
 }
Exemplo n.º 9
0
 /// <summary>
 /// 得到一个集合
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public IEnumerable <T> FindList <T>() where T : class, new()
 {
     return(Dbcontext.Set <T>().ToList());
 }
Exemplo n.º 10
0
 /// <summary>
 /// 获取IQueryable
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="condition"></param>
 /// <returns></returns>
 public IQueryable <T> IQueryable <T>(Expression <Func <T, bool> > condition) where T : class, new()
 {
     return(Dbcontext.Set <T>().Where(condition));
 }
Exemplo n.º 11
0
 /// <summary>
 /// 获取IQueryable
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns></returns>
 public IQueryable <T> IQueryable <T>() where T : class, new()
 {
     return(Dbcontext.Set <T>());
 }
Exemplo n.º 12
0
 /// <summary>
 /// 根据条件查询一个实体
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="condition"></param>
 /// <returns></returns>
 public T FindEntity <T>(Expression <Func <T, bool> > condition) where T : class, new()
 {
     return(Dbcontext.Set <T>().Where(condition).FirstOrDefault());
 }
Exemplo n.º 13
0
 /// <summary>
 /// 根据主键查询一个实体
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="keyValue"></param>
 /// <returns></returns>
 public T FindEntity <T>(object keyValue) where T : class, new()
 {
     return(Dbcontext.Set <T>().Find(keyValue));
 }
Exemplo n.º 14
0
        /// <summary>
        /// 根据条件删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="condition"></param>
        /// <returns></returns>
        public int Delete <T>(Expression <Func <T, bool> > condition) where T : class, new()
        {
            IEnumerable <T> entities = Dbcontext.Set <T>().Where(condition).ToList();

            return(entities.Count() > 0 ? Delete(entities) : 0);
        }
Exemplo n.º 15
0
 /// <summary>
 /// 删除
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="entity"></param>
 /// <returns></returns>
 public int Delete <T>(T entity) where T : class
 {
     Dbcontext.Set <T>().Attach(entity);
     Dbcontext.Set <T>().Remove(entity);
     return(DbTransaction == null?this.Commit() : 0);
 }