MVC 5无法隐式转换类型“System.Linq.IQueryable为bool?(MVC 5 C

2019-10-20 11:49发布

对于我的生活中,我想不通,我怎么得到的错误Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'bool?' 如果我双击它带我到HomeController的错误,并强调该行内选择语句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);
}

任何人都可以请帮助,我要返回的是显示表内的捐赠和人民领域是否是真的还是假的特定记录。

任何帮助我非常感谢:-)

Answer 1:

假设Donations是模型中的布尔字段,你只希望针锋相对ID我觉得你只是想一个记录:

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

要么

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


Answer 2:

问题是这一行:

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

这将尝试匿名类型对象的集合分配到Donations这是可以容纳一个值(可为空)。

所有我想回到的是显示表内的捐赠和人民领域是否是真的还是假的特定记录。

你需要这样的东西:

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

如果你的领域Donations数据库为布尔类型,那么你需要从查询得到的单个实例,即使用First/FirstOrDefaultSingle/SingleOrDefault根据您的要求。

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


文章来源: MVC 5 Cannot implicitly convert type 'System.Linq.IQueryable to bool?