A
A
Anton2019-08-01 10:28:08
ASP.NET
Anton, 2019-08-01 10:28:08

How to create a composite key when merging tables?

I have a method that fills the database with values ​​from a table.

static void PopulateDatabaseStock(OPCDBEntities context, List<StockOnHand> entries,
        out TimeSpan time)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            IEnumerable<StockOnHand> entriesToAdd = EFUtils.MergeEntities(context.StockOnHands, entries, x => x.StockId);

            context.StockOnHands.AddRange(entriesToAdd);
            context.SaveChanges();
            timer.Stop();
            time = timer.Elapsed;
        }

And there is a method that either adds new entries or updates existing ones
/// <summary>
        /// Helps to merge two entity lists together. 
        /// Updates entities in first list matched by provided ID in second list
        /// </summary>
        /// <param name="persistedEntities">Entities in database</param>
        /// <param name="toMergeEntities">Entities not managed by database</param>
        /// <param name="idFn">Identity function. Must return object with valid GetHashCode() and Equals()</param>
        /// <typeparam name="T">Entity class</typeparam>
        /// <typeparam name="ID">Identity class</typeparam>
        /// <returns>list of new entities which were not found in database</returns>
        public static IEnumerable<T> MergeEntities<T, ID>(IEnumerable<T> persistedEntities, 
            IEnumerable<T> toMergeEntities, Func<T, ID> idFn) where T : IUpdatableFrom<T>
        {
            Dictionary<ID, T> persistedDict = persistedEntities.ToDictionary(idFn);

            List<T> toAddEntities = new List<T>();

            foreach (var entity in toMergeEntities)
            {
                ID id = idFn.Invoke(entity);

                if (!persistedDict.ContainsKey(id))
                {
                    toAddEntities.Add(entity);
                }
                else
                {
                    persistedDict[id].TryUpdateFrom(entity);
                }
            }

            return toAddEntities;
        }

Now it checks against the primary key StockId (Guid), but I need it to check against two keys StoreId, PartNumber (because otherwise it just adds the entry again).
Please help me to solve this problem.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question