public TE ToEntity(TM eMap) { TE e = (TE)Activator.CreateInstance(typeof(TE)); var allProps = eMap.GetType().GetProperties() .Select(p => new { attr = p.GetCustomAttributes(true).Where(x => x is ManualBoxingAttribute).FirstOrDefault(), prop = p }).Where(a => !PropertiesToSkip.Contains(a.prop.Name)); //standard mapping var standadProps = allProps.Where(a => a.attr == null); foreach (var mapProp in standadProps.Select(a => a.prop)) { var eProp = typeof(TE).GetProperty(mapProp.Name); if (eProp != null) { MapProperty(eMap, e, mapProp, eProp); } } //manual mapping var manualProps = allProps.Where(a => a.attr != null); manualProps.Where(a => a.attr is ManualBoxingReferenceAttribute).ToList().ForEach(a => { var id = (int)a.prop.GetValue(eMap, null); var eprop = typeof(TE).GetProperty(a.prop.Name); if (id > 0) { var repoTuple = _repoFinder.CreateRepository(eprop.PropertyType); var refEntity = repoTuple.Item2.GetMethod("Get").Invoke(repoTuple.Item1, new object[] { id, Enums.LockMode.None }); eprop.SetValue(e, refEntity, null); } else { eprop.SetValue(e, null, null); } }); manualProps.Where(a => a.attr is ManualBoxingMethodAttribute).ToList().ForEach(a => { var method = e.GetType().GetMethod(((ManualBoxingMethodAttribute)a.attr).UnboxMethodName); method.Invoke(null, new object[] { e, eMap }); }); return(e); }
public void Transform(IBox <TM> box) { EnsureTypesAreValid(); var converter = new NHibernateBoxConverter <TE, TM>(_repoFinder); var entries = converter.ToEntity(box); var entriez = new List <TE>(); //persist (set tu null which to skip) var repo = _repoFinder.CreateRepository <TE>(); foreach (var entry in entries) { var e = FindExistingEntity.Invoke(repo, entry); if (e != null) { switch (ImportStrategy) { case BoxImporterStrategy.ErrorExisting: throw new Exception("Error strategy fired"); break; case BoxImporterStrategy.SkipExisting: _log.Debug(e.Id + " skipped"); entriez.Add(null); break; case BoxImporterStrategy.UpdateExisting: var mapper = ObjectMapperManager.DefaultInstance .GetMapper <TE, TE>(new DefaultMapConfig() .IgnoreMembers <TE, TE>(new[] { "Id" })); mapper.Map(entry, e); var entryx = repo.Update(e); _log.Debug(entryx.Id + " updated"); entriez.Add(entryx); break; case BoxImporterStrategy.RewriteExisting: repo.Delete(e); entry.Id = 0; var entryy = repo.Save(entry); _log.Debug(entryy.Id + " rewritten"); entriez.Add(entryy); break; default: throw new Exception("Unknown import strategy"); break; } } else { entry.Id = 0; var entryy = repo.Save(entry); entriez.Add(entryy); } } if (box.Count() != entriez.Count) { throw new InvalidOperationException("Entyty vs Box count mismatch"); } var result = new List <TE>(); //custom unboxing for (int i = 0; i < box.Count(); i++) { if (entriez[i] != null) { CustomUnboxing(entriez[i], box.Skip(i).First()); result.Add(entriez[i]); } else { result.Add(entries[i]); } } Entries = result; }