1110
1110

Reputation: 6839

EF Many-To-Many saving issue

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.

Upvotes: 0

Views: 69

Answers (1)

Slauma
Slauma

Reputation: 177163

It's not a many-to-many relationship. You need two one-to-many relationships and must expose ItemsInBoards as a model entity:

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;}
}

Then you can write into the association table - including the CreatedOnDate property value - by:

var newItemInBoard = new ItemInBoard
{
    ItemId = model.ItemId,
    BoardId = model.BoardId,
    CreatedOnDate = DateTime.Now
};
con.ItemsInBoard.Add(newItemInBoard);
con.SaveChanges();

Some more details about such a model type are here: https://stackoverflow.com/a/7053393/270591

Upvotes: 1

Related Questions