Last active
August 9, 2017 12:19
-
-
Save mahmut-gundogdu/47611c20977dff2378685f228666e644 to your computer and use it in GitHub Desktop.
iki listedeyi senkron etme. var olanı güncelle , olmayanı sil, yeni olanı ekle. source : https://stackoverflow.com/a/24643014/3928982
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using AutoMapper; | |
using KYGM.Framework.Core.Abstracts.BusinessLayer; | |
namespace KYGM.Web.UI.Helper | |
{ | |
public static class IBusinessExtension | |
{/// <summary> | |
/// Elimizdeki Model list ile Entity List eşitleyen bir fonksiyon | |
/// </summary> | |
/// <typeparam name="TViewModel"></typeparam> | |
/// <typeparam name="TEntity"></typeparam> | |
/// <param name="service">Db ile işlemimizi halledecek</param> | |
/// <param name="modelSet">Veri Kaynağımız</param> | |
/// <param name="entitySetQuery">Eşitlenecek veriyi seçen query</param> | |
/// <param name="sourceKey">Model deki Eslesme Yapacağımız Değer</param> | |
/// <param name="destinationKey">Entitydeki deki Eslesme Yapacağımız Değer</param> | |
/// <param name="setParentKey">Yeni nesnemiz olduğunda çalıştıracağımız kod. Genelde Id ataması yapacağız</param> | |
public static void SyncEntitySet<TViewModel, TEntity>(this IBusiness<TEntity> service, IEnumerable<TViewModel> modelSet, | |
Expression<Func<TEntity, bool>> entitySetQuery, Func<TViewModel, int?> sourceKey, Func<TEntity, int?> destinationKey, Action<TEntity> setParentKey) | |
where TViewModel : class, new() | |
where TEntity : class, new() | |
{ | |
int userId = GeneralHelper.UserId(); | |
var entitySet = service.GetAllQueryable(entitySetQuery); | |
foreach (var entityItem in entitySet) | |
{ | |
var modelItem = modelSet.FirstOrDefault(i => sourceKey(i) == destinationKey(entityItem) && destinationKey(entityItem).HasValue); | |
if (modelItem == null) | |
{ | |
service.Delete(userId, entityItem); | |
} | |
else | |
{ | |
Mapper.Map(modelItem, entityItem); | |
service.Update(userId, entityItem); | |
} | |
} | |
foreach (var modelItem in modelSet) | |
{ | |
if (sourceKey(modelItem) == null) | |
{ | |
var entityItem = Mapper.Map<TEntity>(modelItem); | |
setParentKey(entityItem); | |
service.Add(userId, entityItem); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment