Answer the question
In order to leave comments, you need to log in
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;
}
/// <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;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question