Sequence包含ASP.NET MVC中的多个元素

时间:2015-07-06 12:11:39

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

我想使用单个子类别名称显示产品,但我得到的序列包含多个元素错误。

SubCategory Name传递值以显示Product controller的动作,如下所示

 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);
        }

我有一个这样的菜单视图,

@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>

和类别,子类别&amp;像这样的产品型号

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; }

    }

我有关于子类别的数据是这样的

|Computer=>HP
         =>Lenovo
|Computer=>HP
         =>Lenovo

|Mobile  =>Samsung
         =>Apple
|Mobile  =>Samsung
         =>Apple

如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

  

var subcat = db.SubCategories.Include(“Products”)。Single(s =&gt;   s.SubCategoryName == subcategory);

如果在SubCategories中找到给定subcategory的多个元素,那么由于Single的使用,上面的语句会抛出你提到的错误(Sequence包含多个元素)。因此,不要使用Single,而是使用FirstOrDefault。所以你的代码应该如下所示。

var subcat = db.SubCategories.Include("Products").FirstOrDefault(s => s.SubCategoryName == subcategory);