Reputation: 1435
I'm new with MVC & Entity Framework and trying to track changes. Here is my code snippet:
string historyText = "<ul>";
ICollection<LookUp> oldPositions = fromDB.LookUps;
fromDB.LookUps.Clear();
IEnumerable<LookUp> allPositionTypes = lookUpRepository.GetByLookupTypeId(24);
foreach (var interest in chkPositionType)
{
fromDB.LookUps.Add(allPositionTypes.Where(x => x.LookUpID == Convert.ToInt32(interest)).Single());
if (!oldPositions.Contains(allPositionTypes.Where(x => x.LookUpID == Convert.ToInt32(interest)).Single()))
historyText += "<li>" + "Position Type : <span class='history-old'> </span><span class='history-separator'>|</span><span class='history-new'>" + lkupRepo.GetByID(Convert.ToInt32(interest)).Name + "</span></li>";
}
historyText += "</ul>";
For some reason as soon as I clear Lookups, it sets oldPositions to null too. I would also like to know the ones I added new and those which were deleted but didn't add again. So basically need to track changes.
Is there any alternate way? If its better I can adopt it too.
Upvotes: 2
Views: 330
Reputation: 739
I believe oldPositions is losing reference to fromDB.Lookups when calling the Clear() method.
ICollection oldPositions = fromDB.LookUps;
fromDB.LookUps.Clear();
oldPositions has a reference pointer to fromDB.LookUps collection. fromDB.LookUps collection references to other objects from elements are released, so oldPositions will be empty.
Upvotes: 0
Reputation: 1456
change oldPosition to enumerate of the LookUp, like below
var oldPositions = fromDB.LookUps.ToList();
Remove fromDB.LookUps.Clear() and it should work.
Upvotes: 2