0

这是我正在尝试做的,但它不起作用:

HardwareType hwt = new HardwareType { HType = "PC" };
IEnumerable<Hardware> Pcs = db.Hardware.Where(h => h.HardwareType.Contains(hwt));
ViewBag.Pcs = Pcs.ToString();

那么如何将我的 IEnumerable 转换为字符串(或其他原始数据类型),以便在我尝试在 Razor 中使用它时编译器不会给我一个错误?

@foreach (var item in ViewBag.Pcs) {
     <li><a href="#" class="btn"><i class="icon-hdd"></i> @item.HType</a></li>
}

硬件类:

public class Hardware
    {
        public int Id { get; set; }
        public virtual ICollection<DeviceType> Type { get; set; }
        public string AssetTagId { get; set; }
        public virtual ICollection<Manufacturer> Manufacturer { get; set; }
        [Required]
        [StringLength(50)]
        public string ServiceTagId { get; set; }
        [Required]
        [StringLength(50)]
        public string SerialNumber { get; set; }
        [Required]
        [StringLength(75)]
        public string ProductNumber { get; set; }
       // [Required]
        [StringLength(20)]
        public string PurchaseDate { get; set; }
        [StringLength(20)]
        public string WarrantyExpiration { get; set; }
        [Required]
        [StringLength(20)]
        public string WarrantyType { get; set; }
        public virtual ICollection<Location> Location { get; set; }
        public virtual ICollection<HardwareType> HardwareType { get; set; }
        [Required]
        [StringLength(2000)]
        public string Notes { get; set; }
        public string POATag { get; set; }
    }

硬件类型类:

public class HardwareType
    {
        public int Id { get; set; }
        [Required]
        [StringLength(128)]
        public string HType { get; set; }
        public virtual ICollection<Hardware> Hardware { get; set; }
    }
4

1 回答 1

1

在我看来,好像问题在于您其转换为字符串,在这里:

ViewBag.Pcs = Pcs.ToString();

你为什么这样做?看起来您想要遍历视图中序列中的各个项目。要么使用:

ViewBag.Pcs = Pcs;

或者

ViewBag.Pcs = Pcs.ToList();

如果您想强制实现查询。

编辑:再次查看错误,我怀疑这实际上是Where问题所在的子句。我怀疑你真的想要:

var pcs = db.Hardware.Where(h => h.HardwareType.Any(hwt => hwt.HType == "PC"));
ViewBag.Pcs = pcs.ToList(); // Materialize the query

问题是尝试使用您的hwt值作为查询的输入......

于 2012-12-12T17:02:47.520 回答