首页 > 代码库 > Entity Framework多表多条件动态查询

Entity Framework多表多条件动态查询

方式一  Linq To Entity形式:

/// <summary>
        /// 查询的数据
        /// </summary>
        /// <param name="order">升序asc(默认)还是降序desc</param>
        /// <param name="sort">排序字段</param>
        /// <param name="search">查询条件</param>
        /// <param name="listQuery">额外的参数</param>
        /// <returns></returns>      
        public IQueryable<BasicComponentView> DaoChuData(YKTEntities db, string order, string sort, QueryEntity entity, int userId)
        {
            int? type_id = null;
            int? userComId = null;

            if (userId > 0)
            {
                var d = db.SMUSERTB.Where(x => x.USER_ID == userId).Select(x => new { x.TYPE_ID, x.COMPONENT_ID }).FirstOrDefault();
                type_id = d.TYPE_ID;
                userComId = d.COMPONENT_ID;
            }
            var data = http://www.mamicode.com/from a in db.OMBASICCOMPONENTTB>

方式二 拼接字符串:

     /// <summary>
        /// 查询的数据
        /// </summary>
        /// <param name="YKTEntities">数据访问的上下文</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc(默认)还是降序desc</param>
        /// <param name="search">查询条件</param> 
        /// <param name="listQuery">额外的参数</param>
        /// <returns></returns>      
        public IQueryable<SMROLETB> DaoChuData(YKTEntities db, string order, string sort, string search, params object[] listQuery)
        {
            string where = string.Empty;
            int flagWhere = 0;

            Dictionary<string, string> queryDic = ValueConvert.StringToDictionary(search.GetString());
            if (queryDic != null && queryDic.Count > 0)
            {
                foreach (var item in queryDic)
                {
                    if (flagWhere != 0)
                    {
                        where += " and ";
                    }
                    flagWhere++;

                    if (!string.IsNullOrWhiteSpace(item.Key) && !string.IsNullOrWhiteSpace(item.Value) && item.Key.Equals("STATUS")) //需要查询的列名
                    {
                        where += "it." + item.Key + " = ‘" + item.Value + "‘";
                        continue;
                    }
                    where += "it." + item.Key + " like ‘%" + item.Value + "%‘";
                }
            }
            return db.SMROLETB
                     .Where(string.IsNullOrEmpty(where) ? "true" : where)
                     .OrderBy("it." + sort.GetString() + " " + order.GetString())
                     .AsQueryable();
        }