【发布时间】:2020-06-16 09:10:55
【问题描述】:
我正在尝试使用Include() 加载相关数据,但我认为我做错了什么。
我想在这张桌子上加载鞋子的图像,并将用于练习的图像放在一行中,但是当我添加 ShoeImages.ImageURL(举个例子)时,我收到一个错误 CS1061,我无法显示来自Include()的数据。
我有一个索引页:
@model IEnumerable<Shoes.Data.Entities.ShoeEntity>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.ShoesImages)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<!--- This is the problem too --->
<td>
@Html.DisplayFor(modelItem => item.ShoesImages.ImageURL)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
索引控制器:
public IActionResult Index()
{
var data = _context.Shoes.Include(ci => ci.ShoeImages);
return View(data);
}
Shoe实体:
public class ShoeEntity
{
public string Id { get; set; }
public string Name { get; set; }
public ICollection<ShoeImageEntity> ShoeImages { get; set; }
}
ShoeImages 实体:
public class ShoeImageEntity
{
public string Id { get; set; }
public string ImageURL { get; set; }
public string ImageFullPath =>
string.IsNullOrEmpty(ImageURL) ? null : $"https://localhost:44357{ImageURL.Substring(1)}";
public ShoeEntity Shoe { get; set; }
}
上下文类:
public class DataContext : IdentityDbContext<UserEntity, RoleEntity, string>
{
public DbSet<ShoeEntity> Shoes{ get; set; }
public DbSet<ShoeImagesEntity> ShoesImages { get; set; }
public DataContext(DbContextOptions options) : base(options)
{
}
}
我还尝试了实体框架文档。
【问题讨论】:
-
请发布您的上下文类。
-
在我的帖子中添加了上下文类。数据库是干净的,我正在使用基本设置连接数据库。
-
ShoesImages 是一个集合,你要哪个url?
-
我可以创建鞋子,将图像保存在 wwwroot 文件夹中,然后获取这些图像的 url,但我仍然坚持使用相应图像显示鞋子的数据或将它们适当地加入索引页面(使用 html),甚至无法访问 ShoesImages 属性。我想获取 ImageURL。
-
但是你的 ShoeImages 是一个集合,包含多行。你需要遍历它们或其他东西。
标签: c# asp.net asp.net-mvc asp.net-core entity-framework-core