无法初始化类型"x"因为它没有实现'System.Collections.IEnumerab
本文关键字:quot 实现 IEnumerab Collections System 因为 初始化 类型 | 更新日期: 2023-09-27 17:50:35
我试图使用linq sql和ViewModel连接3个表,将查询传递给视图并显示结果,但它不起作用。
DbContext类:
public partial class DbEntities : DbContext
{
public DbSet<Foo> Foos{ get; set; }
public DbSet<Bar> Bars{ get; set; }
public DbSet<Fubar> Fubars{ get; set; }
}
ViewModel:
public class MyViewModel
{
public Foo Foo{ get; set; }
public Bar Bar{ get; set; }
public Fubar Fubar{ get; set; }
}
控制器:
public ActionResult Index(string searchString)
{
//var db = new MyViewModel(); //wrong
var db = new DbEntities();
var query = (from f in db.Foos
join b in db.Bars on f.IDFoo equals b.IDFoo
join fb in db.Fubars on b.IDBar equals fb.IDBar
select new MyViewModel {
f.IDFoo,
f.NameFoo,
f.CityFoo,
b.NameBar,
fb.NameFubar });
if (!String.IsNullOrEmpty(searchString))
{
query = query.Where(x => x.NameFubar.Contains(searchString));
}
return View(query);
}
视图:
@model IEnumerable<Proj.Models.MyViewModel>
@using (Html.BeginForm())
{
<p>
@Html.TextBox("SearchString")
<input type="submit" class="no-button" value="Search" />
</p>
}
@foreach (var item in Model)
{
<div class="title">@Html.DisplayFor(modelItem => item.NameFubar)</div><br />
...
}
我得到以下错误:
1. "Cannot initialize type 'Proj.Models.MyViewModel' with a collection initializer because it does not implement 'System.Collections.IEnumerable' "
问题是我必须在MyViewModel中设置属性而不是类:
public short IDFoo { get; set; }
public string NameFoo { get; set; }
public string CityFoo { get; set; }
public string NameBar { get; set; }
public string NameFubar { get; set; }
在linq查询中,我使用的是集合初始化项而不是对象初始化项:
select new MyViewModel {
IDFoo = f.IDFoo,
NameFoo = f.NameFoo,
CityFoo = f.CityFoo,
NameBar = b.NameBar,
NameFubar = fb.NameFubar
};
这没什么意义。您正在创建视图模型的新实例,MyViewModel
,其中导航属性不是枚举(!),并尝试加入这些?
你不应该从db上下文的实例开始吗?我相信你应该。
var db = new SomethingThatIsADbContext();
var query = (from f in db.Foos
join b in db.Bars on f.IDFoo equals b.IDFoo
join fb in db.Fubars on b.IDBar equals fb.IDBar
select new MyViewModel {
f.IDFoo,
f.NameFoo,
f.CityFoo,
b.NameBar,
fb.NameFubar }).ToList();
如果你这样写
query = query.Where(x => x.NameFubar.Contains(searchString));
性能很差,你可以在你的linq代码。