MVC 5 Cannot implicitly convert type 'System.Linq.IQueryable to bool?

╄→尐↘猪︶ㄣ 提交于 2019-12-24 18:05:10

问题


For the life of me I cannot figure how I am getting the error Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'bool?' if I double-click the error it takes me to the HomeController and highlights the select statement within the line statsModel.Donations = (from q in db.Shows where (q.Id == 1) select new { q.Donations });.

Show.cs

namespace WebApplication1.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Show
    {
        public int Id { get; set; }
        public Nullable<bool> Donations { get; set; }
    }
}

StatsisticsModel.cs

namespace WebApplication1.Models
{
    using System;

    public class StatisticsModels
    {
        public int UserCount { get; set; }
        public decimal? TotalAmount { get; set; }
        public Nullable<bool> Donations { get; set; }
    }
}

HomeController

[ChildActionOnly]
public ActionResult Statistics()
{
    var statsModel = new StatisticsModels();
    statsModel.UserCount = (from m in db.AspNetUsers where (m.UserName != "someone") && (m.EmailConfirmed == true) select new { m.UserName }).Count();
    statsModel.TotalAmount = db.Donations.Sum(o => o.Amount);
    statsModel.Donations = (from q in db.Shows where (q.Id == 1) select new { q.Donations });
    return View(statsModel);
}

Can anyone please help, all I want to return is whether the Donations and People fields within the Show table are true or false for a particular record.

Any help would me much appreciated :-)


回答1:


Assuming that Donations is a boolean field in your model and you only expect one record for tat ID I think you just want:

statsModel.Donations = (from q in db.Shows where (q.Id == 1) select q.Donations).Single();

or

statsModel.Donations = db.Shows.Where(q => q.Id == 1).Single(q => q.Donations);



回答2:


Problem is with this line:

 statsModel.Donations = (from q in db.Shows where (q.Id == 1) select new { q.Donations });

This will try to assign the a collection of anonymous type object to Donations which is can hold a single value (Nullable).

all I want to return is whether the Donations and People fields within the Show table are true or false for a particular record.

You need something like:

statsModel.Donations = db.Shows.Any(q=> q.Id == 1);

If your field Donations in database is of type boolean, then you need to get a single instance of that from your query, using either First/FirstOrDefault, Single/SingleOrDefault depending on your requirement.

statsModel.Donations = (from q in db.Shows where (q.Id == 1) select q.Donations)
                       .FirstOrDefault();


来源:https://stackoverflow.com/questions/24787942/mvc-5-cannot-implicitly-convert-type-system-linq-iqueryable-to-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!