An explicit conversion exists (do you miss the role?)

I have a method that gives me the groupID, and then I want to receive news based on the GroupID user ID.

public IEnumerable<News> Getnews(int GroupID) { Expression<Func<News, bool>> constraint = null; constraint = e => e.GroupID.Equals(GroupID); return newsRepository.GetMany(constraint); } 

here I call the above method:

 News news = newsService.Getnews(GroupID); 

and this is a mistake:

It is not possible to implicitly convert the type ' System.Collections.Generic.IEnumerable<MeetingBoard.Model.News> ' to MeetingBoard.Model.News . An explicit conversion exists (are you missing a listing?)

+9
source share
6 answers

Getnews returns a collection of news, and your string expects a single news item.

You can try

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

or expect the number

 IEnumerable<News> news = newsService.GetNews(GroupID); 
+14
source

This line sets a variable that is defined as a single News instance for an IEnumerable instance:

 News news = newsService.Getnews(GroupID); 

You want to change to

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

Basically you are trying to install a news compilation in a single news link.

+5
source

Getnews returns an IEnumerable<News> (i.e., several news items), and you are trying to assign it to News news (i.e. one news item). This does not 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 one news item, use FirstOrDefault :

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

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

  • First() : you expect Getnews always return at least one Getnews news. This will throw an exception if the news is not returned.
  • Single() : You expect Getnews always return exactly one Getnews news. This will throw an exception if more than one or zero news is returned.
  • SingleOrDefault() : You expect zero or one message to be returned. This will throw an exception if multiple news items are returned.
+4
source

Is this what you want

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

or maybe something like:

 News news = newsService.Getnews(GroupID).FirstOrDefault(); 
+4
source

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

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

returns the first News if it is found in newRepository , otherwise

+4
source

There is an explicit conversion (are you missing a cast?) I ran into the same problem in my C # code. I wrote code in VS. I checked the complete code and I got the cause of this error. I missed the "I" in my explicit interface name.

Error image

Picture with Error

Solution

Error Solution

-one
source

All Articles