混淆从Linq2Sql中获取一个int的int

时间:2010-02-04 16:30:05

标签: c# .net linq linq-to-sql

我刚学习Linq并遇到了问题。对于某些验证,我从数据库中读取最后一个里程表,需要将其与下一个读数进行比较。里程表读数是传入数据的int,数据库是double(在dbml文件中更改为int)。

以下是我的代码:

private bool IsValidOdometer(string equipment, int odometerReading)
{
    bool returnVariable = true;
    CarteGraphDataDataContext db = new CarteGraphDataDataContext();

    var odometer = (from p in db.EquipmentMainGenerals join q in db.EquipmentFuelLogs 
            on p.wdEquipmentMainGeneralOID equals q.wdEquipmentMainGeneralOID
            where p.VehicleId == equipment
            orderby q.Odometer descending
            select q.Odometer).Take(1);

    int previousOdometer = odometer;

    if (odometer.Count() != 0)
    {
        if (odometerReading < previousOdometer)
        {
            returnVariable = false;
        }
    }

    return returnVariable;
}

问题行是int previousOdometer = odometer;。我得到的错误是:

  

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

而不是Enumerable.Take使用Enumerable.SingleEnumerable.Take将返回IEnumerableEnumerable.Single将返回单个实例(或抛出):

int odometer = (from p in db.EquipmentMainGenerals
                join q in db.EquipmentFuelLogs 
                on p.wdEquipmentMainGeneralOID
                    equals q.wdEquipmentMainGeneralOID
                where p.VehicleId == equipment
                orderby q.Odometer descending
                select q.Odometer).Single();

int previousOdometer = odometer;

另外,我会在这里明确键入odometer,而不是像你那样隐式地输入。

最后你的行

  

CarteGraphDataDataContext db = new CarteGraphDataDataContext();

应该像using这样阻止

using(CarteGraphDataDataContext db = new CarteGraphDataDataContext()) {
    // okay to go
}