表值未显示 - ASP.net

时间:2015-06-11 16:50:10

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

这可能是一个愚蠢的问题,因为我是asp.net中MVC模式的新手。 我正在尝试访问我的数据库中的值,但值不会被渲染 在视图页面上。

这是我写的代码。

“Resturant”模型的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace OdetoFood.Models
{
    [Table("Resturants")]
    public class Resturant
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public ICollection<ResturantReviews> Reviews { get; set; }

    }
}

这是我的DbContext模型:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace OdetoFood.Models
{
    public class OdeToFoodDb : DbContext

    {
        public DbSet<Resturant> Resturants { get; set; }
        public DbSet<ResturantReviews> Reviews { get; set; }
    }
}

控制器类的代码:

public class HomeController : Controller
    {
        OdeToFoodDb _db = new OdeToFoodDb();
        public ActionResult Index()
        {
            var model = _db.Resturants.ToList();

            return View(model);
        }

这是应该显示值的视图:

@model IEnumerable<OdetoFood.Models.Resturant>

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


@foreach (var item in Model)
{
    <h3>@item.Name</h3>
    <div>@item.City, @item.Country</div>
    <div>@item.Id</div>
}

Web.config中的连接字符串设置如下:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-OdetoFood-20150611025411.mdf;Initial Catalog=aspnet-OdetoFood-20150611025411;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

这将是该项目的种子方法:

protected override void Seed(OdeToFood.Models.OdeToFoodDb context)

    {

        context.Restaurants.AddOrUpdate(r => r.Name,

            new Restaurant { Name = "Sabatino's", City = "Baltimore", Country = "USA" },

            new Restaurant { Name = "Great Lake", City = "Chicago", Country = "USA" },

            new Restaurant

            {

                Name = "Smaka",

                City = "Gothenburg",

                Country = "Sweden",

                Reviews =

                 new List<RestaurantReview>{

                      new RestaurantReview{ Rating = 9, Body="Great Food!" }

                  }

            });

    }