尝试更新我的数据库中的多对多关系,如下所示:
DeckCards
(key sign) Deck_id
(key sign) Card_id
我正在尝试通过我的控制器操作来做到这一点:
public ViewResult Add(int id)
{
var cardInDb = _context.Cards.Single(c => c.Id == id);
var deckInDb = _context.Decks.Single(d => d.id == id);
deckInDb.Card.Add(cardInDb);
cardInDb.Deck.Add(deckInDb);
return View("Index");
}
我的观点:
@model YGOBuilder.Models.ViewModels.DeckCardViewModel
<div>
<h4>DeckCardViewModel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Cards.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Cards.Atk)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Atk)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Cards.Def)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Def)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Cards.Desc)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Desc)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Cards.Level)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Level)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Cards.Type)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Type)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Cards.Attribute)
</dt>
<dd>
@Html.DisplayFor(model => model.Cards.Attribute)
</dd>
@foreach (var item in Model.Cards.Card_Images)
{
<dd>
<img src=@item.image_url height="300" width="200" style="margin: 2px">
</dd>
}
</dl>
@foreach (var d in Model.Decks)
{
<ul class="nav navbar-nav navbar-right">
@Html.ActionLink($"Add to: {d.Name} ", "Add", new { id = d.id })
</ul>
}
</div>
我正在寻找的最终结果是数据库表正在更新 DeckCards 表,如下所示:
Deck_Id Card_Id
3 1
ID 为 1 的卡片映射到 Deck 3。
我的模型:
public class Card
{
public int Id { get; set; }
public string Name { get; set; }
public int? Atk { get; set; }
public int? Def { get; set; }
public string Desc {get; set;}
public int? Level { get; set; }
public string Type { get; set; }
public string Attribute { get; set; }
[DisplayName("Image")]
public virtual List<Image> Card_Images { get; set; }
public virtual List<Deck> Deck { get; set; }
}
public class Deck
{
public int id { get; set; }
public string Name { get; set; }
public string Notes { get; set; }
[DisplayName("Card")]
public virtual List<Card> Card { get; set; }
}
当我运行上面的代码时, var cardInDb = _context.Cards.Single(c => c.Id == id); 似乎与 Sequence contains no elements 错误中断。