public virtual void SaveUser(IUser user) { lock (Locker.GetLocker($"BasePermissionStore_SaveUser")) { // 账号不能重复.如果是多租户,同一租户里的账号不能重复. var allUser = GetAllUser(); var existSameAccountUser = false; var sameAccountUsers = allUser.Where(a => a.GetAccount() == user.GetAccount()).ToList(); if (HasTenant(out string tenantId)) { existSameAccountUser = allUser.Any(a => a.GetAccount() == user.GetAccount() && ((ITenant <string>)a).TenantId == tenantId && a.GetKey() != user.GetKey()); } else { existSameAccountUser = allUser.Any(a => a.GetAccount() == user.GetAccount() && a.GetKey() != user.GetKey()); } if (existSameAccountUser) { throw new BusinessException($"已经存在账号为{user.GetAccount()}的用户"); } var userTmp = EasyMap.MapToNew <TUser>(user); var userEntity = _db.Set <TUser>().AddOrUpdate(userTmp, CurrentUserId, CurrentTenantId, null); userEntity.SetName(user.GetName()); userEntity.SetAccount(user.GetAccount()); userEntity.SetPassword(user.GetPassword()); _db.SaveChanges(); _memoryCache.Remove(userCacheKey); } }
/// <summary> /// 保存资源。会从资源id和资源code两字段考虑是新增还是修改,无删除 /// </summary> /// <param name="resources"></param> public virtual void SaveResources(List <IResource> resources) { var allResources = _db.Set <TResource>().ToList(); resources.ForEach(resource => { var resourceKey = resource.GetKey(); var resourceEntity = allResources.FirstOrDefault(a => a.GetKey() == resourceKey || a.GetResourceCode() == resource.GetResourceCode()); if (resourceEntity == null) { //add var addDto = new TResource(); EasyMap.Map(resource.GetType(), typeof(TResource), resource, addDto, null); _db.Add(addDto); DbSetExtenssion.UpdateEntityCommonField(resourceEntity, EEntityOperType.Add, CurrentUserId, CurrentTenantId); } else { EasyMap.Map(resource.GetType(), typeof(TResource), resource, resourceEntity, null); DbSetExtenssion.UpdateEntityCommonField(resourceEntity, EEntityOperType.Update, CurrentUserId, CurrentTenantId); } }); _db.SaveChanges(); _memoryCache.Remove(resourceCacheKey); }
public ESTable(IEnumerable dict) { _dict = new EasyMap <string, IESObject>(); var list = dict.Cast <object>(); list.ForEach(t => _dict.Add(ToString(GetValue(t, "Key")), ToVirtual(GetValue(t, "Value")))); }
public void MapListPerformanceTest() { try { var times = 1000000; var sources = Enumerable.Range(1, 100 * 100 * 100).Select(a => new Source { Name = "1", Age = 1, Birth = DateTime.Now, NoMatch1 = "noMatchField", Week = DayOfWeek.Wednesday }).ToList(); //MapperConfiguration cfg = new MapperConfiguration(c => //{ // c.CreateMap<Source, Target>(); //}); //var autoMap = cfg.CreateMapper(); //Stopwatch autoMapWatch = Stopwatch.StartNew(); //var autoMapTargets = autoMap.Map<List<Source>, List<Target>>(sources); //autoMapWatch.Stop(); Stopwatch expressionWatch = Stopwatch.StartNew(); var expressionsTargets = EasyMap.MapToList <Source, Target>(sources); expressionWatch.Stop(); } catch (Exception ex) { var a = ex; } }
public virtual void SaveRole(IRole role) { lock (Locker.GetLocker($"BasePermissionStore_SaveRole")) { var roleTmp = EasyMap.MapToNew <TRole>(role); _db.Set <TRole>().AddOrUpdate(roleTmp, CurrentUserId, CurrentTenantId, null); _db.SaveChanges(); _memoryCache.Remove(roleCacheKey); } }
/// <summary> /// 保存资源。会从资源id和资源code两字段考虑是新增还是修改 /// </summary> /// <param name="resource"></param> public virtual void SaveResource(IResource resource) { var resourceTmp = EasyMap.MapToNew <TResource>(resource); var resourceEntity = _db.Set <TResource>().AddOrUpdate(resourceTmp, CurrentUserId, CurrentTenantId); resourceEntity.SetName(resourceTmp.GetName()); resourceEntity.SetParentKey(resourceTmp.GetParentKey()); _db.SaveChanges(); _memoryCache.Remove(resourceCacheKey); }
/// <summary> /// 实体列表的差异更新,包含增加、删除、更新 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TDto"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="entities"></param> /// <param name="existsEntities"></param> /// <param name="dtos"></param> /// <param name="userId"></param> /// <param name="tenantId"></param> public static void AddOrUpdateList <TEntity, TDto, TKey>(this DbSet <TEntity> entities, List <TEntity> existsEntities, List <TDto> dtos, TKey userId, TKey tenantId = default) where TEntity : class, IIdField <TKey>, new() where TDto : class, IIdField <TKey> { AddOrUpdateListInternal(entities, existsEntities, dtos, sourceDto => EasyMap.MapToNew <TEntity>(sourceDto), (sourceDto, entityDto) => EasyMap.Map(sourceDto.GetType(), entityDto.GetType(), sourceDto, entityDto, null), userId, tenantId); }
public static TEntity AddOrUpdate <TEntity, TDto, TKey>(this DbSet <TEntity> entities, TDto dto, TKey userId, TKey tenantId = default, List <TEntity> existEntities = null) where TEntity : class, IIdField <TKey>, new() where TDto : class, IIdField <TKey> { return(AddOrUpdateInternal(entities, dto, sourceDto => EasyMap.MapToNew <TEntity>(sourceDto), (sourceDto, entityDto) => EasyMap.Map(sourceDto.GetType(), entityDto.GetType(), sourceDto, entityDto, null), userId, tenantId, existEntities)); }
public void MapToNewTest() { try { var sourceType = typeof(Source); var targetType = typeof(Target); var includeFields = new List <string> { "Name", "Age", "Birth", "Week", "ExceptField" }; Expression <Func <Target, object> > includeSelector = t => new { t.Name, t.Age, t.Birth, t.Week }; var exceptFields = new List <string> { "ExceptField" }; Expression <Func <Target, object> > exceptSelector = t => new { t.ExceptField }; var source = new Source { Name = "zhoujing", Age = 30, Birth = new DateTime(1989, 1, 1), NoMatch1 = "未匹配的字段,不会赋值到target", Week = DayOfWeek.Wednesday, ExceptField = "这个是排除的字段", NotIncludeField = "这个是不包含字段" }; var target = new Target(); target.Clear(); target = (Target)EasyMap.MapToNew(sourceType, targetType, source, includeFields); Assert.True(IsMatch(source, target, false, true)); target.Clear(); target = EasyMap.MapToNew <Target>(source); Assert.True(IsMatch(source, target, false, false)); target.Clear(); target = EasyMap.MapToNew <Source, Target>(source); Assert.True(IsMatch(source, target, false, false)); target.Clear(); target = EasyMap.MapToNew <Source, Target>(source, includeFields); Assert.True(IsMatch(source, target, false, true)); target.Clear(); target = EasyMap.MapToNew(source, includeSelector, exceptSelector); Assert.True(IsMatch(source, target, true, true)); target.Clear(); target = EasyMap.MapToNew <Source, Target>(source, includeFields, exceptFields); Assert.True(IsMatch(source, target, true, true)); } catch (Exception ex) { throw; } }
public void MapSinglePerformanceTest() { try { var times = 1000000; var source = new Source { Name = "1", Age = 1, Birth = DateTime.Now, NoMatch1 = "noMatchField", Week = DayOfWeek.Wednesday }; var target = new Target(); //MapperConfiguration cfg = new MapperConfiguration(c => //{ // c.CreateMap<Source, Target>(); //}); //var autoMap = cfg.CreateMapper(); //Stopwatch autoMapWatch = Stopwatch.StartNew(); //for (int i = 0; i < times; i++) //{ // autoMap.Map(source, target, typeof(Source), typeof(Target)); //} //autoMapWatch.Stop(); var sourceType = typeof(Source); var targetType = typeof(Target); Stopwatch expressionWatch = Stopwatch.StartNew(); var mapAction = EasyMap.GetMapAction <Source, Target>(); for (int i = 0; i < times; i++) { mapAction(source, target, null);// 最快,比automap快5倍 //EasyMap.Map(source, target,null); // 和automap差不多 //EasyMap.Map(sourceType, targetType, source, target, null); // 为automap的5倍时间 } expressionWatch.Stop(); } catch (Exception ex) { var a = ex; } }
static void Main(string[] args) { var myMap = new MyDic <int, string>(); myMap.Add(new Item <int, string>(1, "One")); myMap.Add(new Item <int, string>(2, "Two")); myMap.Add(new Item <int, string>(3, "Three")); myMap.Add(new Item <int, string>(4, "Four")); myMap.Add(new Item <int, string>(5, "Five")); foreach (var item in myMap) { Console.Write(item + " "); } Console.WriteLine(); Console.WriteLine(myMap.Search(6) ?? "Not found"); myMap.Remove(4); myMap.Remove(2); foreach (var item in myMap) { Console.Write(item + " "); } Console.WriteLine(); var easyMap = new EasyMap <int, string>(); easyMap.Add(new Item <int, string>(1, "One")); easyMap.Add(new Item <int, string>(2, "Two")); easyMap.Add(new Item <int, string>(3, "Three")); foreach (var item in easyMap) { Console.Write(item + " "); } Console.WriteLine(); Console.WriteLine(easyMap.Search(5) ?? "Not found"); Console.WriteLine(easyMap.Search(2) ?? "Not found"); Console.ReadLine(); }
static void Main() { var easyMap = new EasyMap <int, string> { new Item <int, string>(1, "Один"), new Item <int, string>(2, "Два"), new Item <int, string>(3, "Три"), new Item <int, string>(4, "Четыре"), new Item <int, string>(5, "Пять") }; Console.WriteLine("Вывод EasyMap"); Print(easyMap); Console.WriteLine("Поиск элемента по ключу 3"); Console.WriteLine(easyMap.Search(3) ?? "Не найдено"); Console.WriteLine(); Console.WriteLine("Поиск элемента по ключу 7"); Console.WriteLine(easyMap.Search(7) ?? "Не найдено"); Console.WriteLine(); Console.WriteLine("Удалим элемент с ключом 2 и выведем результат"); easyMap.Remove(2); Print(easyMap); Console.WriteLine("Очистим словарь"); easyMap.Clear(); Print(easyMap); Console.WriteLine("Dict------------------"); var dict = new Dict <int, string>(10) { new Item <int, string>(1, "Один"), new Item <int, string>(2, "Два"), new Item <int, string>(3, "Три"), new Item <int, string>(4, "Четыре"), new Item <int, string>(5, "Пять"), new Item <int, string>(11, "Одиннадцать"), new Item <int, string>(12, "Двенадцать"), new Item <int, string>(22, "Двадцать Два") }; dict.Add(new Item <int, string>(23, "Двадцать три")); dict.Add(new Item <int, string>(111, "Сто одиннадцать")); Console.WriteLine("Вывод Dict"); Print(dict); Console.WriteLine($"Словарь имеет максимальный размер = {dict.Count}"); Console.WriteLine("Пробуем добавить еще элемент (44, Сорок четыре)"); dict.Add(new Item <int, string>(44, "Сорок четыре")); Console.WriteLine("Вывод Dict"); Print(dict); Console.WriteLine("Поиск элемента по ключу 3"); Console.WriteLine(dict.Search(3) ?? "Не найдено"); Console.WriteLine(); Console.WriteLine("Поиск элемента по ключу 7"); Console.WriteLine(dict.Search(7) ?? "Не найдено"); Console.WriteLine(); Console.WriteLine("Удалим элемент с ключом 2 и выведем результат"); dict.Remove(2); Print(dict); Console.WriteLine("Поиск элемента по ключу 22"); Console.WriteLine(dict.Search(22) ?? "Не найдено"); Console.WriteLine(); Console.WriteLine("Удалим элемент с ключом 22 и выведем результат"); dict.Remove(22); Print(dict); Console.WriteLine("Удалим элемент с ключом 23 и выведем результат"); dict.Remove(23); Print(dict); Console.WriteLine("Очистим словарь"); dict.Clear(); Print(dict); }
/// <summary> /// 增加单个实体,会用EasyMap做实体映射 /// 请在外部提交更改 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TDto"></typeparam> /// <typeparam name="TKey"></typeparam> /// <param name="entities"></param> /// <param name="dto"></param> /// <param name="userId"></param> /// <param name="tenantId"></param> public static void Add <TEntity, TDto, TKey>(this DbSet <TEntity> entities, TDto dto, TKey userId, TKey tenantId = default) where TEntity : class, IIdField <TKey>, new() { AddInternal(entities, dto, sourceDto => EasyMap.MapToNew <TEntity>(sourceDto), userId, tenantId); }
public ESTable(Dictionary <string, IESObject> dict) { _dict = new EasyMap <string, IESObject>(dict); }
public ESTable() { _dict = new EasyMap <string, IESObject>(); }