将不确定变成确定~LINQ查询两种写法,性能没有影响,优化查询应该是“按需查询”
如果在linq中希望进行一对多的复合查询时,请直接在查询中使用join into,或者使用let 关键字,当然在建立实体时动态赋值对于查询的性能也是没有影响的,两次查询结果完成相同
一 :在实体中赋值
var linq = from data in this.GetModel() join data2 in iWebDepartmentsRepository.GetModel() on data.DepartmentID equals data2.DepartmentID select new WebManageUsers_Ext { ManageUserID = data.ManageUserID, LoginName = data.LoginName, WebDepartments_Extend = data2, WebManageUser_WebManageRoles_Extend = new WebManageUser_WebManageRolesRepository().GetModel().Where(i => i.ManageUserID == data.ManageUserID), AvatarUrl = data.AvatarUrl, };
在语句中使用let关键字
var linq = from data in this.GetModel() join data2 in iWebDepartmentsRepository.GetModel() on data.DepartmentID equals data2.DepartmentID let list = new WebManageUser_WebManageRolesRepository().GetModel().Where(i => i.ManageUserID == data.ManageUserID) select new WebManageUsers_Ext { ManageUserID = data.ManageUserID, LoginName = data.LoginName, WebDepartments_Extend = data2, WebManageUser_WebManageRoles_Extend = list, AvatarUrl = data.AvatarUrl, };
两次的SQL分析器的结果是完成一样的
当然,对于LINQ的查询,最好的方式就是“按需”查询,也就是说,用到哪些字段就select哪些字段,代码可能是这样:
var linq = from data in db.WebManageUsers join data2 in db.WebDepartments on data.DepartmentID equals data2.DepartmentID let list1 = db.WebManageUser_WebManageRoles.Where(i => i.ManageUserID == data.ManageUserID).Select(j => new WebManageUser_WebManageRoles_Ext { ManageRoleID = j.ManageRoleID, ManageUserID = j.ManageUserID }) select new WebManageUsers_Ext { ManageUserID = data.ManageUserID, LoginName = data.LoginName, RealName = data.RealName, WebDepartments_Extend = new WebDepartments_Ext { DepartmentName = data2.DepartmentName }, WebManageUser_WebManageRoles_Extend = list1, };
回到目录