I have a simple Many to Many. Categories on Products. Each has a virtual List of the other. I create a product like this:
product = new Product()
{
AccountId = this.AccountId,
Name = this.ProductName,
Price = this.ProductPrice,
Slug = this.ProductSlug,
Sku = this.ProductSku,
Favorite = true,
Categories = new List<Category>()
{
category
}
};
product.Id = productManager.Save(product);
Then, when I go to save it, it won't save the many to many. I've googled and tried quite a few different variations of this code, and still nothing:
public new String Save(Product data)
{
try
{
var entity = GetById(data.Id);
if (entity == null)
{
this.Context.Set<Product>().Add(data);
}
else
{
this.Context.Entry(entity).CurrentValues.SetValues(data);
}
data.Id = this.Context.SaveChanges();
var product = Context.Products
.Include("Categories")
.FirstOrDefault(t => t.Id == data.Id);
/**
* Categories
*/
var categories = this.Context.Categories
.Where(t => t.AccountId == data.AccountId);
var productCategories = new List<Category>();
if (data.SelectedCategoryIds != null && data.SelectedCategoryIds.Any())
{
productCategories.AddRange(categories
.Where(category => data.SelectedCategoryIds.Contains(category.Id)));
}
product.Categories.Clear();
product.Categories.AddRange(productCategories);
this.Context.SaveChanges();
return data.Id;
}
catch (Exception ex)
{
Log.Error(ex);
return null;
}
}
What am I missing here? Why will it not persist my many to many Categories?