简体   繁体   中英

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

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 :-)

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);

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM