public class StoreController : Controller
{
// GET: /Store/
ProductsStoreEntities storeDB = new ProductsStoreEntities();
public ActionResult Index()
{
var items = storeDB.item.ToList();
return PartialView(items);
}
索引视图
model IEnumerable<MvcProductsStore.Models.Item>
@{
ViewBag.Title = "Store";
}
<h3>Browse Products:</h3>
<p>
Select from @Model.Count()
Products:
</p>
<ul>
@foreach (var item in Model)
{
<li>@Html.ActionLink(item.IName,"Browse", new { item = item.IName })</li>
}
</ul>
示例数据
namespace MvcProductsStore.Models
{
public class SampleData : DropCreateDatabaseIfModelChanges<ProductsStoreEntities>
{
protected override void Seed(ProductsStoreEntities context)
{
var items = new List<Item>
{
new Item {ItemId = 1000, IName = "Patches"},
new Item {ItemId = 2000,IName = "Jewelry"},
new Item {ItemId = 3000, IName = "Wood Working"}
};
items.ForEach(s => context.item.Add(s));
}
}
模型
namespace MvcProductsStore.Models
{
public class ProductsStoreEntities : DbContext
{
public DbSet<Product> products { get; set; }
public DbSet<Item> item { get; set; }
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
没有真正返回错误,但是当我点击商店时它告诉我从0项中选择。因此,不是拿起项目列表,而是计数为0。
答案 0 :(得分:1)
您没有在种子方法之后保存数据库上下文对象 所以你应该添加
context.SaveChanges();
样本数据部分中的种子方法
答案 1 :(得分:0)
请更改返回View()而不是PartialView()。
public class StoreController : Controller
{
// GET: /Store/
ProductsStoreEntities storeDB = new ProductsStoreEntities();
public ActionResult Index()
{
var items = storeDB.item.ToList();
return View(items);
}