2015-10-14 35 views
1

我已經創建了一個linq查詢來檢查數據庫表中是否存在一個項目,工作得很好。 現在我想從表中獲取價值並將其放入unitOfMeasure中。基於linq查詢獲取數據庫值

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

使用FirstOrDefault

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

感謝@gaganJaura這工作就像一個魅力。 –

0

您可以使用.First

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