0

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!

4

2 回答 2

0

我现在通过添加项目和交易的平面结构来解决它。就像物品和交易上的多对多一样。

由于我知道每件物品的所有者,所以我还可以通过在交易上添加 senderId 和 returnerId 来排序发送者和返回者。

这就是我的模型现在的样子。

物品

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Trade> Trades { get; set; }
}

贸易

public class Trade
{
    public int TradeId { get; set; }
    public virtual UserProfile SendUser { get; set; }
    public virtual UserProfile ReturnUser { get; set; }     
    public virtual ICollection<Item> Items { get; set; }
}

这暂时有效..

于 2013-10-14T18:18:40.557 回答
0

这:“一个项目只属于一个行业,但一个行业可以有很多项目。” 听起来像一对多?

如果您可以不使用从 Item 到 Trade 的反向引用,那么映射将会简单得多。

此模型无需任何配置即可映射:

public class Trade
{
    public int Id { get; set; }
    public virtual ICollection<Item> ItemsToSend { get; set; }
    public virtual ICollection<Item> ItemsToReturn { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
}

使用此代码插入数据:

        var trade = new Trade
        {
            ItemsToReturn = new [] { new Item{ Name = "Item to return 1"}, new Item{ Name = "Item to return 2"}},
            ItemsToSend = new [] { new Item{ Name = "Item to send 1"}, new Item{ Name = "Item to send 2"} }
        };
        context.Trades.Add(trade);

        context.SaveChanges();

将生成一个如下所示的 Item 表:

在此处输入图像描述

还有一个 Trades 表,其中包含一行和一个 Id 列。

如果您需要从一个项目导航到它所属的交易,您可以通过查询来做到这一点。

例如,要获得 id = 3 的商品所属的交易,您可以这样做:

using (var db = new TradingContext())
{               
    var tradeOfItem3 = db.Trades.
        FirstOrDefault(t => t.ItemsToReturn.Any(i => i.Id == 3) || t.ItemsToSend.Any(i => i.Id == 3));
}
于 2013-10-14T18:30:33.737 回答