Asp.net mvc 按类别浏览,不返回任何元素
我正在尝试为一个类别显示产品。我得到这个错误消息:序列不包含任何元素。我有一个桌子产品和一个桌子类别。每种产品都标识为一个类别 HomeController.csAsp.net mvc 按类别浏览,不返回任何元素,asp.net-mvc,c#-4.0,Asp.net Mvc,C# 4.0,我正在尝试为一个类别显示产品。我得到这个错误消息:序列不包含任何元素。我有一个桌子产品和一个桌子类别。每种产品都标识为一个类别 HomeController.cs public ActionResult Browse(string nomCategorie) { var categorieModel = db.Categories.Include("Produits") <== the error happened here
public ActionResult Browse(string nomCategorie)
{
var categorieModel = db.Categories.Include("Produits") <== the error happened here
.Single(g => g.NomCategorie == nomCategorie);
return View(categorieModel);
}
公共操作结果浏览(字符串名称分类)
{
var categorieModel=db.Categories.Include(“产品”)g.nomcegorie==nomcegorie);
返回视图(分类模型);
}
浏览.cshtml
@model MVCWebStore.Models.Categorie
@{
ViewBag.Title = "Browse";
}
<h2>Browse Categorie: @Model.NomCategorie</h2>
<ul>
@foreach (var produit in Model.Produits)
{
<li>
@produit.Description
</li>
}
</ul>
@model MVCWebStore.Models.Categorie
@{
ViewBag.Title=“浏览”;
}
浏览Categorie:@Model.nomcegorie
@foreach(Model.Produits中的var produit)
{
-
@产品说明
}
Produit.cs
namespace MVCWebStore.Models
{
using System;
using System.Collections.Generic;
public partial class Produit
{
public Produit()
{
this.ItemPaniers = new HashSet<ItemPanier>();
}
public int IdProduit { get; set; }
public int IdCategorie { get; set; }
public string NomProduit { get; set; }
public string Description { get; set; }
public double Prix { get; set; }
public int Quantite { get; set; }
public virtual Categorie Categorie { get; set; }
public virtual ICollection<ItemPanier> ItemPaniers { get; set; }
}
}
名称空间MVCWebStore.Models
{
使用制度;
使用System.Collections.Generic;
公共部分类产品
{
公共产品
{
this.ItemPaniers=newhashset();
}
public int IdProduit{get;set;}
公共int-IdCategorie{get;set;}
公共字符串NomProduit{get;set;}
公共字符串说明{get;set;}
公共双优先级{get;set;}
公共整数量化{get;set;}
公共虚拟分类分类{get;set;}
公共虚拟ICollection ItemPaniers{get;set;}
}
}
分类
名称空间MVCWebStore.Models
{
使用制度;
使用System.Collections.Generic
public partial class Categorie
{
public Categorie()
{
this.Produits = new HashSet<Produit>();
}
public int IdCategorie { get; set; }
public string NomCategorie { get; set; }
public virtual ICollection<Produit> Produits { get; set; }
}
}
公共部分类分类
{
公共分类()
{
this.Produits=new HashSet();
}
公共int-IdCategorie{get;set;}
公共字符串NomCategory{get;set;}
公共虚拟ICollection产品{get;set;}
}
}
您的数据上下文很可能无法正确加载。
连接设置可能有问题。确保datacontext
不为空
如果问题不在于此,则表的创建/链接可能不正确
另外,EF对孩子们的数据也有点奇怪。绝对不是最好的框架。请粘贴类别
和产品
的模型。您尝试过将Single更改为FirstorDefault吗?@user3311522我得到了进一步的信息,但在浏览中失败,在这一行显示了相同的错误消息browse Category:@model。NomCategorie@user3311522抱歉,错误消息是对象引用未设置为对象的实例。似乎是@model.nomcegorie,它在此处停止