using System; using System.Collections.Generic; using System.Linq; using OpenAuth.Repository.Domain; using OpenAuth.Repository.Interface; namespace OpenAuth.App { public class RevelanceManagerApp { public IUnitWork _unitWork { get; set; } /// /// 添加关联 /// 比如给用户分配资源,那么firstId就是用户ID,secIds就是资源ID列表 /// /// 关联的类型,如"UserResource" public void Assign(string type, string firstId, string[] secIds) { Assign(type, secIds.ToLookup(u => firstId)); } public void Assign(string key, ILookup idMaps) { DeleteBy(key, idMaps); _unitWork.BatchAdd((from sameVals in idMaps from value in sameVals select new Relevance { Key = key, FirstId = sameVals.Key, SecondId = value, OperateTime = DateTime.Now }).ToArray()); _unitWork.Save(); } /// /// 删除关联 /// /// 关联标识 /// 关联的<firstId, secondId>数组 public void DeleteBy(string key, ILookup idMaps) { foreach (var sameVals in idMaps) { foreach (var value in sameVals) { _unitWork.Delete(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value); } } } /// /// 取消关联 /// /// 关联的类型,如"UserResource" /// The first identifier. /// The sec ids. public void UnAssign(string type, string firstId, string[] secIds) { DeleteBy(type, secIds.ToLookup(u =>firstId)); } public void DeleteBy(string key, params string[] firstIds) { _unitWork.Delete(u => firstIds.Contains(u.FirstId) && u.Key == key); } /// /// 添加新的关联 /// /// 关联标识 /// 关联的<firstId, secondId>数组 public void AddRelevance(string key, ILookup idMaps) { DeleteBy(key, idMaps); _unitWork.BatchAdd((from sameVals in idMaps from value in sameVals select new Relevance { Key = key, FirstId = sameVals.Key, SecondId = value, OperateTime = DateTime.Now }).ToArray()); _unitWork.Save(); } /// /// 根据关联表的一个键获取另外键的值 /// /// 映射标识 /// 返回的是否为映射表的第二列,如果不是则返回第一列 /// 已知的ID列表 /// List<System.String>. public List Get(string key, bool returnSecondIds, params string[] ids) { if (returnSecondIds) { return _unitWork.Find(u => u.Key == key && ids.Contains(u.FirstId)).Select(u => u.SecondId).ToList(); } else { return _unitWork.Find(u => u.Key == key && ids.Contains(u.SecondId)).Select(u => u.FirstId).ToList(); } } } }