I have a database table:
Item{ItemId ...}
Item{BoardId ...}
ItemsInBoards{ItemId, BoardId, CreatedOnDate}
I have a models in my application
public class Item
{
public int ItemId{get;set;}
...
public virtual ICollection<Board> Boards { get; set; }
}
public class Board
{
public int BoardId{get;set;}
...
public virtual ICollection<Item> Items { get; set; }
}
Saving…
...
Item item = con.Item.Find(model.ItemId); // Find item by ID
// Try to save
Board b = con.Boards.Find(model.BoardId); // Find a board by ID
b.CreatedOnDate = DateTime.Now; // This is the issue
item.Boards.Add(b);
con.SaveChanges();
And it’s saved but without CreatedOnDate. I don’t know how to set CreatedOnDAte field to save it in database.
It’s not a many-to-many relationship. You need two one-to-many relationships and must expose
ItemsInBoardsas a model entity:Then you can write into the association table – including the
CreatedOnDateproperty value – by:Some more details about such a model type are here: https://stackoverflow.com/a/7053393/270591