I have an entity that needed a list of type int. Due to this being an internal tool that only I would use, I didn't want to spend a lot of time making a UI/view to edit the list and I sort of cheated.
So, I have the following class:
myitem.cs
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
virtual public ICollection<Size> Sizes {get;set;}
size.cs
public int ID { get; set; }
public int Size { get; set; }
Between the controller and view controller, I did some funky bits. I had a single text field in the view controller called "Sizes" and I then split the input on a comma to an array, and assign the list to Sizes.
This works perfectly and as expected.
string[] sizes = model.sizes.Split(',');
myitem.size = new List<sizes>();
foreach (string item in sizes)
{
myitem.size.Add( new sizes {Size=int.Parse(item)});
}
In the edit one, I find the object, and create a new text string that basically gets all of them and this also works.
In the edit saving controller, no matter what I try, it seems to append. So, I basically did the following:
MyItem myitem = db.myitems.find(id);
...auto mapper stuff from viewmodel to model...
myitem.sizes=null;
...call same bits as create to split and add to sizes...
db.savechanges();
However, I am now finding that whatever I try to do in edit, it simply adds to the list in addition to what is already there - I can't seem to find a way to remove it.
I have tried many different things (instead of = null, foreach and remove(), and a few others) without much luck.
In the end, I don't think this is the best approach at all as I am going to end up dropping the items and recreating them by the thousands for the sake of saving a few minutes, so, I am going to create a DBSet for sizes and do an ajax interface to list/delete/add them separate to the main model. (If there is an easy way, please let me know?!)
However, the fact that this didn't work has annoyed me and I was wondering if anyone knows why?