我正在尝试使用linq连接3个表到sql和ViewModel,将查询传递给View并显示结果,但它不起作用。
更新
DbContext类:
public partial class DbEntities : DbContext
{
public DbSet<Foo> Foos{ get; set; }
public DbSet<Bar> Bars{ get; set; }
public DbSet<Fubar> Fubars{ get; set; }
}
视图模型:
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' "
答案 0 :(得分:2)
这没有多大意义。您正在创建视图模型的新实例MyViewModel
,其中导航属性不是枚举(!)并尝试加入这些?
您是否应该从数据库上下文的实例开始?我相信你应该。
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();
答案 1 :(得分:2)
问题是我必须在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
};
答案 2 :(得分:0)
如果你写这个
query = query.Where(x => x.NameFubar.Contains(searchString));
表现非常差,你可以在你的linq代码中。