【发布时间】:2019-09-13 16:09:42
【问题描述】:
我已将 api 调用中的数据保存到我的数据库中,但在尝试将数据打印到页面时,我得到一个未设置为对象实例的对象引用错误:对象引用未设置为实例的一个对象。我正在尝试访问我的卡片详细信息视图中的 image_url 属性,但它一直在中断
我的模特:
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 IList<Image> Card_Images { get; set; }
public IList<Deck> Deck { get; set; }
}
public class Image
{
public int Id { get; set; }
public string image_url { get; set; }
public string image_url_small{ get; set; }
}
我的控制器操作:
public ActionResult Details(int id)
{
var card = _context.Cards.SingleOrDefault(c => c.Id == id);
if (card == null)
return HttpNotFound();
return View(card);
}
我的数据库表等(在 VS 服务器资源管理器中显示):
Cards
Id (key sign here)
Name
Atk
Def
Desc
Level
Type
Attribute
Images
Id (key sign here)
image_url
image_urul_small
Card_Id
我的看法:
@model YGOBuilder.Models.Card
<div>
<h4>Card</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Atk)
</dt>
<dd>
@Html.DisplayFor(model => model.Atk)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Def)
</dt>
<dd>
@Html.DisplayFor(model => model.Def)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Desc)
</dt>
<dd>
@Html.DisplayFor(model => model.Desc)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Level)
</dt>
<dd>
@Html.DisplayFor(model => model.Level)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Type)
</dt>
<dd>
@Html.DisplayFor(model => model.Type)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Attribute)
</dt>
<dd>
@Html.DisplayFor(model => model.Attribute)
</dd>
<dt>
@Html.DisplayFor(model => model.Card_Images)
</dt>
@foreach (var item in Model.Card_Images)
{
foreach (var i in item.image_url)
{
<td>
<img src=@i height="300" width="200">
</td>
}
}
</dl>
</div>
<p>
@Html.ActionLink("Back to List", "Index")
</p>
我正在尝试通过连接到我的模型的 image_url 属性来显示在视图上,但它似乎在这里绊倒了:
@foreach (var item in Model.Card_Images)
【问题讨论】:
-
Model.Card_Images中的模型应该小写吗? -
没有任何东西可以设置
Card_Images。这是代码优先还是数据库优先? -
@GabrielLuci 这是代码优先 :)
-
@InfiniteHigh 小写不起作用
-
这两个类由 Id 连接,因此您必须确保模型显示 Id 用于链接两个表。
标签: c# .net database entity-framework