I have a class called Item
which references the next item and the previous item.
public class Item
{
private Item() { }
public Item(string itemName)
{
ItemId = Guid.NewGuid();
ItemName = itemName;
}
public Guid ItemId { get; set; }
public string ItemName { get; set; }
public Guid NextItemId { get; set; }
public virtual Item NextItem { get; set; }
public Guid PreviousItemId { get; set; }
public virtual Item PreviousItem { get; set; }
public Guid GroupId { get; set; }
public virtual Group Group { get; set; }
}
I have another table called Group
it is for grouping it items.
public class Group
{
private Group() { }
public Group(string groupName)
{
GroupId = Guid.NewGuid();
GroupName = groupName;
GroupItems = new List<Item>();
}
public void AddGroupItem(Item item)
{
if (Items.Count == 0)
{
Items.Add(item);
}
else
{
item.PreviousItem = Items.Last();
item.PreviousItemId = Items.Last().ItemId;
Items.Last().NextItem = item;
Items.Last().NextItemId = item.ItemId;
Items.Add(item);
}
}
public Guid GroupId { get; set; }
public string GroupName { get; set; }
public virtual IList<GroupItem> GroupItems { get; set; }
}
Here's how I create and save items and their group.
Group group1 = new Group("first group");
Item item1 = new Item("item 1");
Item item2 = new Item("item 2");
Item item3 = new Item("item 3");
group1.AddItem(item1);
group1.AddItem(item2);
group1.AddItem(item3);
_context.Add(group1);
_context.SaveChanges();
How do I write the OnModelCreating
to handle the two references to the same table.