EF-按字段读取


        /// <summary>
        /// 直接获取特定一个或者多个字段的值
        /// 多个字段需要声明Model
        /// var s=  testDal.GetScalar<dynamic>(m=>m.Code== "02018",m=>new { m.Name,m.Code });
        /// var a = s.Name;
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="predicate"></param>
        /// <param name="scalar"></param>
        /// <returns></returns>
        public T GetScalar<T>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, T>> scalar)
        {
            if (predicate == null)
            {
                return dbcontext.Set<TEntity>().AsNoTracking().Select(scalar).FirstOrDefault();
            }
            else
            {
                return dbcontext.Set<TEntity>().AsNoTracking().Where(predicate).Select(scalar).FirstOrDefault();
            }

        }
posted on 2017-02-03 23:40  雪夜  阅读(162)  评论(0编辑  收藏  举报