这是我正在尝试做的,但它不起作用:
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; }
}
HardwareType类:
public class HardwareType
{
public int Id { get; set; }
[Required]
[StringLength(128)]
public string HType { get; set; }
public virtual ICollection<Hardware> Hardware { get; set; }
}
答案 0 :(得分: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
值用作输入来查询...