SQL语句结合上下文查询(in查询)
在多个表联合查询时,使用linq语句查询就显得不那么方便了,执行效率也不高,
SQL语句查询的优势就显现出来了。
using (var context = new YZS_TRAEntities()) { using (Domain.HRModelsContainer hr = new Domain.HRModelsContainer()) {var officeEntities = context.事务所主任.Where(f => officeIds.Contains(f.事务所主任ID)).ToList(); #region 获取该协议所有的对象 var mobileEntities = officeEntities.Select(f => f.手机.Trim()).ToList(); string mobile = string.Join(",", mobileEntities); //List数组的每个元素加上引号,如("12","32","5456","876455") string s1 = string.Format("'{0}'", mobile.Replace(",", "','")); string sql = string.Format(@"SELECT d.Name [DepartName],c.Name [Position],c.No [PostNo],a.Mobile [EmployeePhone] FROM [HYSYZSCCODB].[dbo].[Employee] a //[DepartName] [Position] [PostNo] [EmployeePhone] 是实体officeDTO定义的字段,即转对象 inner join [HYSYZSCCODB].[dbo].[DPEAss] q on a.Id=q.EmployeeId inner join [HYSYZSCCODB].[dbo].[Post] c on q.PostId=c.Id inner join [HYSYZSCCODB].[dbo].[Department] d on d.Id = c.DepartmentId where q.IsHistory='false' and a.Mobile" + " in " + "(" + s1 + ")");
//where a.IsValid='true' and q.IsHistory='false' and {0} order by a.[Index] desc",
//DepartId.HasValue ? "a.Id='" + (Guid)DepartId + "'" + "or " + "a.PDepartmentId='" + (Guid)DepartId + "'" : "1=1");
var entitys = hr.Database.SqlQuery<OfficeDTO>(sql).ToList(); #endregion } }
LIst数组的元素转字符串,(以便用于in查询)
var mobileEntities = officeEntities.Select(f => f.手机.Trim()).ToList(); string mobile = string.Join(",", mobileEntities); //List数组的每个元素加上引号,如("12","32","5456","876455") string s1 = string.Format("'{0}'", mobile.Replace(",", "','"));