【发布时间】:2017-11-26 07:31:36
【问题描述】:
我是使用 Linq 的 MVC 新手,在我的项目中,我收到一个错误:
传入字典的模型项是“System.Boolean”类型,但该字典需要一个“System.Collections.Generic.IEnumerable`1[Parts.PartsLocation]”类型的模型项。
我将 MVC 与 EF 一起使用,那么如何返回 IEnumerable?
这是我的控制器:
public async Task<ActionResult> Index(String aContainer)
{
var container = from x in db.PartsLocations select x;
var empty = from y in db.PartsLocations select y;
if (!String.IsNullOrEmpty(aContainer))
{
var parent = from a in db.PartsLocations
where (a.LocationName == aContainer)
select a.ParentLocation;
return View(await parent.ToListAsync());
}
empty = empty.Where(r => r.LocationName.Contains(null));
return View(await empty.ToListAsync());
}
查看:
@model IEnumerable<Parts.PartsLocation>
@{
ViewBag.Title = "Index";
}
型号:
namespace Parts
{
using System;
using System.Collections.Generic;
public partial class PartsLocation
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public PartsLocation()
{
this.ManufacturingParts = new HashSet<ManufacturingPart>();
}
public int LocationID { get; set; }
public int TypeID { get; set; }
public string LocationName { get; set; }
public string Description { get; set; }
public int PlantID { get; set; }
public Nullable<int> BayID { get; set; }
public Nullable<int> SecurityGroupID { get; set; }
public Nullable<int> ParentLocation { get; set; }
public Nullable<System.DateTime> LastMoved { get; set; }
public string Notes { get; set; }
public virtual LocationType LocationType { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ManufacturingPart> ManufacturingParts { get; set; }
public virtual ManufacturingPlant ManufacturingPlant { get; set; }
}
}
【问题讨论】:
-
你能发布你的模型代码吗?
-
对不起,我现在用 Model 编辑了。
-
这是否发生在传入的字符串为空/空的情况下?这应该返回满足 IEnumerable 的 List
。突出的一件事是 empty = empty.Where(r => r.LocationName.Contains(null));这看起来应该是 empty = empty.Where(r=> null == r.LocationName); -
页面加载时返回一个空视图。然后传入一个字符串,我希望它返回一个记录集的整数类型(ParentLocation),其中传入的字符串与列 LocationName 匹配。似乎它与where子句中的Linq有关。
-
@Steve Py - 当我传入有效的字符串类型时会发生这种情况。如果它为 null,则将返回一个空视图。
标签: asp.net-mvc entity-framework linq