/// <summary> /// Updates a collection of items from a collection of item views. Existing items are updated or deleted. New items are added. /// </summary> /// <typeparam name="TChild">The database item</typeparam> /// <typeparam name="TChildView">A view of this database item. Matching items have same Id</typeparam> /// <param name="connection">The database connection</param> /// <param name="currentValues">The current value from the database</param> /// <param name="newValues">The new values</param> /// <param name="factory">A factory that create a new item</param> /// <param name="updater">A delegate that updates an existing item</param> public static List <TChild> UpdateCollectionFromViews <TChild, TChildView>(this IFolkeConnection connection, IReadOnlyCollection <TChild> currentValues, IReadOnlyCollection <TChildView> newValues, Func <TChildView, TChild> factory, Func <TChildView, TChild, bool> updater) where TChild : class, IFolkeTable, new() where TChildView : class, IFolkeTable, new() { var ret = new List <TChild>(); if (currentValues == null || !currentValues.Any()) { foreach (var childValue in newValues) { var child = factory(childValue); ret.Add(child); connection.Save(child); } return(ret); } var newValueToAdd = newValues.Where(x => currentValues.All(y => y.Id != x.Id)); foreach (var currentValue in currentValues) { var newValue = newValues.FirstOrDefault(x => x.Id == currentValue.Id); if (newValue == null) { connection.Delete(currentValue); } else { if (updater != null && updater(newValue, currentValue)) { connection.Update(currentValue); } ret.Add(currentValue); } } foreach (var childDto in newValueToAdd) { var child = factory(childDto); ret.Add(child); connection.Save(child); } return(ret); }
/// <summary> /// Update a Product. Returns null if the provided product cannot be found in the database. /// </summary> /// <param name="product"></param> /// <returns></returns> public Product Update(Product product) { using (var t = session.BeginTransaction()) { // Get the "old" product information from db // and update them with the new info Product oldProduct = session.Get <Product>(product.Id); if (oldProduct == null) { return(oldProduct); } oldProduct.Comment = product.Comment; oldProduct.Description = product.Description; oldProduct.Name = product.Name; oldProduct.PartNumber = product.PartNumber; oldProduct.Price = product.Price; session.Update(oldProduct); t.Commit(); return(oldProduct); } }