An explicit conversion exists (are you missing a cast?)

后端 未结 6 662
礼貌的吻别
礼貌的吻别 2020-12-10 13:06

I have a method that gives me the groupID of users and then I want to get the news based on the user\'s GroupID.

public IEnumerable Getnews(int G         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 13:45

    Getnews returns an IEnumerable (i.e. multiple News) and you are trying to assign it to News news (i.e. a single News item). That doesn't work.

    There are two possibilities, depending on what you want to do.

    If you want to use all the news, change News news to IEnumerable:

    IEnumerable news = newsService.Getnews(GroupID);
    

    If you want to use only a single news, use FirstOrDefault:

    News news = newsService.Getnews(GroupID).FirstOrDefault();
    

    Depending on what you expect, you also could use one of the following:

    • First(): You expect Getnews to always return at least one news. This will throw an exception if no news are returned.
    • Single(): You expect Getnews to always return exactly one news. This will throw an exception if more than one or zero news are returned.
    • SingleOrDefault(): You expect zero or one news to be returned. This will throw an exception if more than one news are returned.

提交回复
热议问题