Excuse my confusing title, but its not easy to say it in short.
I'm having problems defining a many-to-many relationship in my code first model. This is my first project using the code first framework, and I need some help.
I got two models, Item
and Trade
. And the story behind it all is that im building a item trading website.
A trade involve one or many items beeing sent from person A to person B, and one or many items are sent back from person B to person A, completing the trade.
One item belongs to one trade only, but one trade can have many items.
This is how my models look so far.
Item
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public int TradeId { get; set; }
[ForeignKey("TradeId")]
public virtual Trade Trade { get; set; }
}
Trade
public class Trade
{
public int TradeId { get; set; }
public virtual ICollection<Item> ItemsToSend { get; set; }
public virtual ICollection<Item> ItemsToReturn { get; set; }
}
But when trying to run update-database
I get the following error.
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Items_dbo.Trades_TradeId". The conflict occurred in database "MyDB", table "dbo.Trades", column 'TradeId'.
Any help is much appreciated, thanks!