Cannot implicitly convert type 'System.Linq.IQueryable' to 'int?'

前端 未结 6 1794
梦毁少年i
梦毁少年i 2021-02-06 23:14
var cityList = from country in 
                    doc.Element(\"result\")
                    .Element(\"cities\")
                    .Descendants(\"city\")
select ne         


        
相关标签:
6条回答
  • 2021-02-06 23:24

    it will return an iQueryable, you will need to do something like using the First

    cit.CountryID = db.Countries.First(a=>a.DOTWInternalID == citee.CountryCode).ID
    
    0 讨论(0)
  • 2021-02-06 23:26

    It has elapsed a long time since the last update to the post but i think it's worth improving the solution.

    In my opinion the solutions posted for this particular scenario are not the best way in terms of performace to get the ID you need. A better solution is as follows.

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

    The previous statemants basically runs a SQL query similar to the following one:

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

    The proposed solutions work but basically do a "SELECT *" to create the entity with all the values and then obtain the ID from the object just created.

    You can use Linqpad to actually see the generated SQL and tune up LINQ queries or Lambdas.

    Hope it helps to some others that get to this post.

    0 讨论(0)
  • 2021-02-06 23:29
    cit.CountryID = db.Countries.First(a=>a.DOTWInternalID == citee.CountryCode).ID
    
    0 讨论(0)
  • 2021-02-06 23:34

    As the error message says, your Linq query returns an System.Linq.IQueryable (for all intents and purposes a collection of ints). If you'd like to get one of them, you can either call First or ElementAt(n) to get the n'th element.

    0 讨论(0)
  • 2021-02-06 23:41

    IQueryable is not a single int - but a query that can represent a collection.

    0 讨论(0)
  • 2021-02-06 23:42

    Here is the problem and solution

    from cnt in db.Countries where cnt.DOTWInternalID == citee.CountryCode select cnt.ID part. If you omit the ID then it returns a Generic IEnumerable with Country(hoping that you have Country class). So what you have to do is first return the select criteria and select the first row then the ID field. Same like shown below.

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

    This will solve your problem.

    0 讨论(0)
提交回复
热议问题