标签:
第一步:
var userids = entityPairs.Select(p => p.Item1.OwnerId).ToList(); var userMapping = (context.Set<User>() .Where(u => userids.Contains(u.Id)) .Select(u => new { id = u.Id, username = u.Username, nickname = u.Nickname, }).ToDictionary(u => u.id, u => u));
第二步:
pair.Item2["Username"] = userMapping.GetOrDefault((long)pair.Item1.OwnerId).nickname;
示列代码一:管理员获取
/// <summary> /// 选择需要的字段 /// </summary> [Tested("Common.Test.Admin.AdminAdminsControllerTest")] public void Select(EntireDbContext context, IList<Tuple<Admin, IDictionary<string, object>>> entityPairs) { // 获取关联的用户和角色名称 var adminIds = entityPairs.Select(p => p.Item1.Id).ToList(); var userMapping = (context.Set<User>() .Where(u => adminIds.Contains(u.Id)) .Select(u => new { id = u.Id, username = u.Username, nickname = u.Nickname, roleId = u.RoleId, roleName = u.Role.Name // 这里会转换成join }).ToDictionary(u => u.id, u => u)); foreach (var pair in entityPairs) { pair.Item2["Id"] = pair.Item1.Id; pair.Item2["SuperAdmin"] = ( pair.Item1.SuperAdmin ? BooleanValues.True : BooleanValues.Null); pair.Item2["CreateTime"] = pair.Item1.CreateTime.ToClientTimeString(); pair.Item2["Username"] = userMapping.GetOrDefault(pair.Item1.Id)?.username; pair.Item2["Nickname"] = userMapping.GetOrDefault(pair.Item1.Id)?.nickname; pair.Item2["RoleName"] = userMapping.GetOrDefault(pair.Item1.Id)?.roleName; pair.Item2["RoleId"] = userMapping.GetOrDefault(pair.Item1.Id)?.roleId; } }
标签:
原文地址:http://www.cnblogs.com/zhongku/p/4822286.html