首页 > 解决方案 > Can not implicitly convert type system.collection.genaric.list to DataModel.resturant.cuisine

问题描述

I find many other questions on the same problem but I can't get any solution

This is my handler function for searching a cuisine in database

    public Cuisine GetCuisines(string cuisine)
    {

        using (ResturantContext context = new ResturantContext())
        {
            // db.Cuisines.Where(x => x.Name.Contains(Cuisine))
            return (from m in context.Cuisines
                       .Include("Images")
                       .Include("Category")
                    where m.Name == cuisine
                    select m).ToList();
        }
    }

what is the problem here I can't find out

标签: c#asp.net-mvclinq

解决方案


ToList() creates a List<Cuisines> but your method returns a single Cuisine.

You should either change the return type of the method to List<Cuisines>:

public List<Cuisine> GetCuisines(string cuisine)

...or call FirstOrDefault() instead of ToList() to select only a single Cuisines:

using (ResturantContext context = new ResturantContext())
{
    return (from m in context.Cuisines
                .Include("Images")
                .Include("Category")
            where m.Name == cuisine
            select m).FirstOrDefault();
}

FirstOrDefault() will return null if no matching Cuisines was found. Single() will throw an exception.


推荐阅读