C# 为什么可以';我不能引用ICollection中的属性吗?

C# 为什么可以';我不能引用ICollection中的属性吗?,c#,asp.net,asp.net-core,razor-pages,C#,Asp.net,Asp.net Core,Razor Pages,我只想打印一些图像的路径,它们存储在Image模型的path属性中,但我不能打印,因为这是一个ICollection 以下示例是可能的,因为它不是ICollection @Html.DisplayFor(modelItem => item.Category.Name) 这是我的控制器页面 正如你所看到的,我尝试了一些方法希望找到答案 当我调试时,我可以看到属性,我只需要路径 我甚至已经试过了 @Html.DisplayFor(modelItem => item.Image.

我只想打印一些图像的路径,它们存储在
Image
模型的
path
属性中,但我不能打印,因为这是一个ICollection

以下示例是可能的,因为它不是ICollection

@Html.DisplayFor(modelItem => item.Category.Name)

这是我的控制器页面

正如你所看到的,我尝试了一些方法希望找到答案

当我调试时,我可以看到属性,我只需要
路径

我甚至已经试过了

@Html.DisplayFor(modelItem => item.Image.Select(a => a.Path))
但这样做我会得到一个:

 InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
运行时错误

有人能帮我吗?提前谢谢

编辑:产品型号代码

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebApp.Models
{
    public class Product
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
        [Column(TypeName = "decimal(18,2)")]
        public decimal Price { get; set; }

        public int CategoryId { get; set; }
        public Category Category { get; set; }

        public ICollection<Image> Image { get; set; }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations.Schema;
使用System.Linq;
使用System.Threading.Tasks;
名称空间WebApp.Models
{
公共类产品
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
[列(TypeName=“十进制(18,2)”)]
公共十进制价格{get;set;}
public int CategoryId{get;set;}
公共类别{get;set;}
公共ICollection映像{get;set;}
}
}

Razorview不适用于类接口和Genneric。您可以为尝试引用的
列表设置路径,而不是单个字符串值

您不能引用这样的集合,您需要遍历每个项以获取其值

一种方法是:

@foreach (var item in Model.Product)
{
   <tr>
        @foreach (var image in item.Image)
        {
            <td>@image.Path</td>
        }    
   </tr>
}
@foreach(Model.Product中的变量项)
{
@foreach(item.image中的var图像)
{
@图像路径
}    
}

根据上一个屏幕截图,它看起来像
@item。Image
属性本身就是一个集合。您需要在该集合上执行另一个循环,以提取该集合中每个实例的属性。您可以显示产品模型代码吗?如果item.Image是一个集合,即您的产品有很多图像,您应该迭代它,显示集合中每个图像的路径。请文本,而不是图像。@AussieJoe,产品型号代码增加了很多感谢,它解决了。你能告诉我为什么使用
Product=await\u context.Product.Include(p=>p.Image).ToListAsync()吗起作用,但当我声明一个
公共IList映像{get;set;}
并将其属性设置为
Image=await\u context.Image.ToListAsync()这边?它实际上抛出了
NullReferenceException:Object reference未设置为对象的实例。
@AlissonFabiano我猜您的图像实体在您的上下文中为null,而您的产品实体不为null。您需要对其进行调试,以了解_context.Image为空的原因。可能是数据库映射错误。