Reputation: 10439
I want to send out a notification e-mail when an Item has been assigned to a Category, but it should only happen during the first occurrence. Subsequent Category assignments to an Item do not require a notification to be sent out.
There is a 'Linked' field that will be flagged as true when a Category has been assigned to an Item. Tried using the if (item.Linked == true)
condition as a trigger but a notification is sent out every time a Category is added or removed.
Here's the code so far:
private void UpdateItemCategories(Item item, ItemViewModel viewModel)
{
var itemCategories = item.Categories.ToList();
foreach (var category in itemCategories)
{
if (!viewModel.Categories.Any(t => t.CategoryId == category.CategoryId))
{
item.Categories.Remove(category);
if (issue.Solutions.Count == 0)
{
issue.Linked = false;
}
}
}
foreach (var category in viewModel.Categories)
{
if (!itemCategories.Any(t => t.CategoryId == category.CategoryId))
{
var itemCategory = category.ToCategory();
db.Categories.Attach(itemCategory);
item.Categories.Add(itemCategory);
item.Linked = true;
}
}
if (item.Linked == true)
{
//Send notification e-mail
UserMailer.Notification(item).Send();
}
}
There clearly is something wrong with the code. Any ideas?
Upvotes: 0
Views: 56
Reputation: 1668
Your logic is not correct. Whenever an item category is updated you should check whether item category is being updated first time or not. This you can check by simply checking whether your item is already linked or not.
Correction in your code:
private void UpdateItemCategories(Item item, ItemViewModel viewModel)
{
//Check whether item is already linked with some category
bool sendEmail;
if(item.Linked == false)
{
sendEmail=true;
}
//Above code is for your understanding. you can simply use: bool sendEmail = !item.Linked;
var itemCategories = item.Categories.ToList();
foreach (var category in itemCategories)
{
if (!viewModel.Categories.Any(t => t.CategoryId == category.CategoryId))
{
item.Categories.Remove(category);
item.Linked = false;
}
}
foreach (var category in viewModel.Categories)
{
if (!itemCategories.Any(t => t.CategoryId == category.CategoryId))
{
var itemCategory = category.ToCategory();
db.Categories.Attach(itemCategory);
item.Categories.Add(itemCategory);
item.Linked = true;
}
}
if (sendEmail)
{
//Send notification e-mail
UserMailer.Notification(item).Send();
}
}
Upvotes: 1