根据linq查询获取数据库值

时间:2015-10-14 12:41:54

标签: c# mysql linq

我创建了一个linq查询来检查数据库表中是否存在一个项目,该工作正常。 现在我想从表中获取值并输入unitOfMeasure。

string quantityUomIngredient = request.Form.Get("QuantityUomIngredient");
string[] quantityUomIngredientArray = quantityUomIngredient.Split();

string uom = quantityUomIngredientArray[1];
int unitOfMeasure;
bool checkUOM = (from x in db.UnitOfMeasures where x.Abbreviation == uom select x).Count() > 0;
if (checkUOM)
    {
    unitOfMeasure = from x in db.UnitOfMeasures
                    where x.Abbreviation == uom
                    select x.UnitOfMeasureId;
    }

如何从数据库中获取此值?

2 个答案:

答案 0 :(得分:2)

使用FirstOrDefault

unitOfMeasure = (from x in db.UnitOfMeasures
                    where x.Abbreviation == uom
                    select x.UnitOfMeasureId).FirstOrDefault();

答案 1 :(得分:0)

您可以使用.First

unitOfMeasure = (from x in db.UnitOfMeasures
                    where x.Abbreviation == uom
                    select x.UnitOfMeasureId).First<int>();