我有一个数据库表:
Item{ItemId ...}
Item{BoardId ...}
ItemsInBoards{ItemId, BoardId, CreatedOnDate}
我的应用程序中有模型
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; }
}
保存...
...
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();
它已保存但没有CreatedOnDate
。我不知道如何设置CreatedOnDAte
字段以将其保存在数据库中。
答案 0 :(得分:1)
这不是多对多的关系。您需要两个一对多关系,并且必须将ItemsInBoards
公开为模型实体:
public class Item
{
public int ItemId{get;set;}
...
public virtual ICollection<ItemInBoard> ItemsInBoard { get; set; }
}
public class Board
{
public int BoardId{get;set;}
...
public virtual ICollection<ItemInBoard> ItemsInBoard { get; set; }
}
public class ItemInBoard
{
[Key, Column(Order = 1)]
public int ItemId{get;set;}
[Key, Column(Order = 2)]
public int BoardId{get;set;}
public DateTime CreatedOnDate{get;set;}
public virtual Item Item{get;set;}
public virtual Board Board{get;set;}
}
然后您可以通过以下方式写入关联表 - 包括CreatedOnDate
属性值 -
var newItemInBoard = new ItemInBoard
{
ItemId = model.ItemId,
BoardId = model.BoardId,
CreatedOnDate = DateTime.Now
};
con.ItemsInBoard.Add(newItemInBoard);
con.SaveChanges();
有关此类型号的更多详情,请访问:https://stackoverflow.com/a/7053393/270591