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

后端 未结 6 660
礼貌的吻别
礼貌的吻别 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<News> (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<News>:

    IEnumerable<News> 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.
    0 讨论(0)
  • 2020-12-10 13:51

    An explicit conversion exists (are you missing a cast?) I was facing same problem in my C# code. I was writing code in VS. I checked full code, and I get reason behind this error. I missed 'I' in my explicit Interface name.

    Picture with Error

    Error Solution

    0 讨论(0)
  • 2020-12-10 13:52

    Getnews returns a collection of news items, and your line is expecting a single news item.

    You could try

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

    or expect an ineumerable

    IEnumerable<News> news = newsService.GetNews(GroupID);
    
    0 讨论(0)
  • 2020-12-10 13:53

    This is what you want

    IEnumerable<News> news = newsService.Getnews(GroupID);
    

    or maybe something like:

    News news = newsService.Getnews(GroupID).FirstOrDefault();
    
    0 讨论(0)
  • 2020-12-10 13:58

    This line is setting a variable which is defined as a single instance of News to an instance of IEnumerable :

    News news = newsService.Getnews(GroupID);
    

    You want to change to

    IEnumerable<News> = newsService.Getnews(GroupID);
    

    Basically you are trying to set a collection of News to a single reference of News.

    0 讨论(0)
  • 2020-12-10 14:00

    return newsRepository.GetMany(constraint); returns an IEnumerable<News>, you should do:

     return newsRepository.GetMany(constraint).FirstOrDefault();
    

    return the first News if it is found in newRepository, null otherwise

    0 讨论(0)
提交回复
热议问题