I want to display products using single subcategory name but I am getting Sequence contains more than one element error.
SubCategory Name passes value to show action of Product controller which is like this
public ActionResult show(string subcategory)
{
if (subcategory == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var subcat = db.SubCategories.Include("Products").Single(s => s.SubCategoryName == subcategory);
if (subcat == null)
{
return HttpNotFound();
}
return View(subcat);
}
I have a menu view like this,
@model IEnumerable<mTest.Models.Category>
<div>
<ul>
@foreach (var category in Model)
{
<li class="active has-sub"><a href="#"><span>@category.CategoryName</span></a>
<ul>
@foreach (var subcategory in category.SubCategories)
{
<li class="has-sub"><a href="/Products/show?subcategory=@subcategory.SubCategoryName"><span>@subcategory.SubCategoryName</span></a></li>
}
</ul>
</li>
}
</ul>
</div>
and Category, subcategory & product model like this
public class Category
{
public Category()
{
Products = new HashSet<Product>();
SubCategories = new HashSet<SubCategory>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<SubCategory> SubCategories { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class SubCategory
{
public SubCategory()
{
Products = new HashSet<Product>();
}
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
I have Data on subcategory is like this
|Computer=>HP
=>Lenovo
|Computer=>HP
=>Lenovo
|Mobile =>Samsung
=>Apple
|Mobile =>Samsung
=>Apple
How to solve this issue.
var subcat = db.SubCategories.Include("Products").Single(s => s.SubCategoryName == subcategory);
If more than one element is found in SubCategories
for a given subcategory
, then because of Single
usage, above statement will throw error mentioned by you (Sequence contains more than one element). So instead of using Single
, use FirstOrDefault
. So your code should be as shown below.
var subcat = db.SubCategories.Include("Products").FirstOrDefault(s => s.SubCategoryName == subcategory);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.