通过linq查询获取数据库值

本文关键字:数据库 获取 查询 linq 通过 | 更新日期: 2023-09-27 18:17:35

我已经创建了一个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;
    }

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

通过linq查询获取数据库值

使用FirstOrDefault

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

您可以使用.First

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