使用 Entity Framework 查询数据库并在视图中显示结果

Querying database with Entity Framework and displaying the results in a view

我遇到了以下问题。我正在尝试查询使用代码优先方法创建的数据库,并在我的视图中显示查询结果。

这是我的模型class :

public class AddApartmentViewModel
{
    public string City { get; set; }
}

public class SearchViewModel
{
    public string Query { get; set; }
}

这是我的搜索控制器

public class SearchController : Controller
{
    private ApartmentContext db = new ApartmentContext();

    [HttpPost]
    public ActionResult Search(SearchViewModel model)
    {
        var results = db.Apartments.ToList();
        return View(results);
    }
}

这是我的搜索栏,我试图将其用作部分视图

@using (Html.BeginForm("Search", "SearchController"))
{ 
    @Html.TextBox("Query")
    <input type="submit" value="Search">
}

整个想法是像这个例子一样显示搜索结果

http://www.zoopla.co.uk/to-rent/property/aberdeen/

如何管理这个?

如果您想使用 entity framework 获得具有搜索功能的列表视图,我强烈建议您阅读这篇文章。

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application