本文主要是介绍Entity Framework多视图条件查询、排序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Entity Framework在C#中常常用于底层和数据库交互,也就是DAL层。而Entity Framework中与数据库交互时底层与数据库通讯的重要的容器就是DbContext。
而使用DbContext对数据库联表查询是最常见的操作。这里介绍多视图联合查询的加条件,等一些内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;namespace RBIM.COMMON
{public static class PredicateBuilder{/// <summary>/// 机关函数应用True时:单个AND有效,多个AND有效;单个OR无效,多个OR无效;混应时写在AND后的OR有效 /// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static Expression<Func<T, bool>> True<T>() { return f => true; }/// <summary>/// 机关函数应用False时:单个AND无效,多个AND无效;单个OR有效,多个OR有效;混应时写在OR后面的AND有效 /// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static Expression<Func<T, bool>> False<T>() { return f => false; }public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,Expression<Func<T, bool>> expr2){var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());return Expression.Lambda<Func<T, bool>>(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);}public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,Expression<Func<T, bool>> expr2){var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());return Expression.Lambda<Func<T, bool>>(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);}}
}
数据接口实现层:
/// <summary>///获取所有数据TransducerConfiguration/// </summary>public IList<FindStressDetectionByProjectKey> GetStressDetectionInfoList(Dictionary<string, string> dicparams){try{Expression<Func<FindStressDetectionByProjectKey, bool>> searchPredicate = PredicateBuilder.True<FindStressDetectionByProjectKey>();foreach (string key in dicparams.Keys){string condition = string.Empty;switch (key.ToLower()){case "projectkey": //case自己扩展 condition = dicparams[key];searchPredicate = searchPredicate.And(c => c.ProjectKey.ToString() == condition);break;case "smsid":condition = dicparams[key];searchPredicate = searchPredicate.And(c => c.Smsid == condition);break;case "tdh":condition = dicparams[key];searchPredicate = searchPredicate.And(c => c.TDH == condition);break;default:break;}}return _dbContext.FindStressDetectionByProjectKey.Where(searchPredicate.Compile()).OrderByDescending(c => c.ID).ToList();}catch (EntityException e){throw e.InnerException;}而UI层调用时:
Dictionary<string, string> dicparams = new Dictionary<string, string>(); IList list = HardwareServiceFacade.hardwareService.SoapService.GetStressDetectionInfoList(dicparams).ToList();
这篇关于Entity Framework多视图条件查询、排序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!