查询数据库但返回null

时间:2015-11-09 20:02:55

标签: asp.net-mvc asp.net-mvc-5

我正在尝试将我的数据库中的项目列入我的视图,但我正在返回null。

我知道连接必须在某种程度上起作用,因为在我的数据库中,表不存在,但是一旦我运行程序,它确实创建了表。但是当我在我的表中添加内容时,我的视图仍然返回NULL。

此外,还没有触及Review表,只是担心让餐厅工作。

Restaurant.cs

namespace OdeToFood.Models
{
    public class Restaurant
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public ICollection<RestaurantReview> Reviews { get; set; }
    }
}

OdeToFood.cs

namespace OdeToFood.Models
{
    public class OdeToFoodDb : DbContext
    {
        public DbSet<Restaurant> Restaurants { get; set; }
        public DbSet<RestaurantReview> Reviews { get; set; }
    }
}

控制器

OdeToFoodDb _db = new OdeToFoodDb();

public ActionResult Index()
{
    var model = _db.Restaurants.ToList();

    return View();
}

Index.cshtml

@model IEnumerable<OdeToFood.Models.Restaurant>

@{ 
    ViewBag.Title = "Home Page";
}

@{
    if (Model != null)
    {
        foreach (var item in Model)
        {
            <div>
                <h4>@item.Name</h4>
                <div>@item.City, @item.Country</div>
                <hr />
            </div>
        }
    }
    else
    {
        <h1>Null</h1>
    }
}

2 个答案:

答案 0 :(得分:3)

您需要将模型传递回视图。

OdeToFoodDb _db = new OdeToFoodDb();

public ActionResult Index()
{
    var model = _db.Restaurants.ToList();

    return View(model);
}

答案 1 :(得分:2)

您实际上从未将模型发送到视图。将其作为论据传递:

OdeToFoodDb _db = new OdeToFoodDb();

public ActionResult Index()
{
    var model = _db.Restaurants.ToList();

    return View(model);
}

此外,最好不要在共享范围内创建数据库上下文。保持上下文尽可能接近其使用位置,并且只在您真正需要时扩展其范围。像这样:

public ActionResult Index()
{
    using (var _db = new OdeToFoodDb())
    {
        var model = _db.Restaurants.ToList();
        return View(model);
    }
}

共享范围内的数据库上下文/连接只是问题,除非您密切关注您正在做的事情。随着代码变得越来越复杂,其他方法更有可能尝试使用它,并且当时它可能处于未知状态。