繁体   English   中英

无法将类型'System.Linq.IQueryable <int>'隐式转换为'int?'

[英]Cannot implicitly convert type 'System.Linq.IQueryable<int>' to 'int?'

var cityList = from country in 
                    doc.Element("result")
                    .Element("cities")
                    .Descendants("city")
select new {
        Name = country.Element("name").Value,
        Code = country.Element("code").Value,
        CountryCode = int.Parse(country
                      .Element("countrycode")
                      .Value)
    };

foreach(var citee in cityList)
{
    City city = new City();
    city.CountryID = from cnt in db.Countries 
                     where cnt.DOTWInternalID == citee.CountryCode 
                     select cnt.ID;
}

我在第二个查询中收到错误,如本文标题所示。 我尝试将int转换为nullable int但没有任何效果。 帮我,伙计们。

谢谢

它会返回一个iQueryable,你需要做一些像使用First的东西

cit.CountryID = db.Countries.First(a=>a.DOTWInternalID == citee.CountryCode).ID

自上次更新帖子以来已经过了很长时间,但我认为值得改进解决方案。

在我看来,针对此特定方案发布的解决方案并不是获得所需ID的最佳方式。 更好的解决方案如下。

db.Countries.Where(a=>a.DOTWInternalID == citee.CountryCode)
            .Select(a => a.ID).FirstOrDefault();

以前的statemants基本上运行类似于以下的SQL查询:

SELECT TOP (1) ID
FROM [dbo].[Countries]
WHERE DOTWInternalID = 123

建议的解决方案可以工作,但基本上做一个"SELECT *"来创建具有所有值的实体,然后从刚创建的对象中获取ID。

您可以使用Linqpad实际查看生成的SQL并调整LINQ查询或Lambdas。

希望它有助于其他一些人来到这篇文章。

这是问题和解决方案

来自db.Countries中的cnt,其中cnt.DOTWInternalID == citee.CountryCode选择cnt.ID部分。 如果省略ID,则返回带有Country的Generic IEnumerable(希望您有Country类)。 所以你要做的就是首先返回选择标准,然后选择第一行,然后选择ID字段。 同样如下所示。

cit.CountryID = (from cnt in db.Countries where cnt.DOTWInternalID == citee.CountryCode   select cnt).First<Country>().ID;

这将解决您的问题。

IQueryable不是单个int - 而是可以表示集合的查询。

正如错误消息所示,您的Linq查询返回一个System.Linq.IQueryable(所有意图和目的都是一组int)。 如果您想获得其中一个,您可以调用FirstElementAt(n)来获取第n个元素。

cit.CountryID = db.Countries.First(a=>a.DOTWInternalID == citee.CountryCode).ID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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