我正在使用ASP.NET MVC,並且在使用實體框架在兩個表之間進行聯接時遇到問題。使用實體框架C與參考表進行聯接#
在這種情況下,我有一個正在查詢:
return db.GENERIC_INGREDIENTS
.Where(genericIngredient => genericIngredient.STATUS_CODE_ID == enabledId)
.AsEnumerable()
.Select(genericIngredient => GenericIngredientToViewModelWithUnitLabel(genericIngredient, languageId))
.OrderBy(genericIngredient => genericIngredient.Name);
但我需要用表db.GENERIC_INGREDIENTS.INGREDIENTS一個連接,然後過濾器適用於CAN_BE_USED屬性。我嘗試了很多方法來做到這一點,但我遇到了問題。我想,我更接近我想要的查詢如下:
return db.GENERIC_INGREDIENTS
.Where(genericIngredient => genericIngredient.STATUS_CODE_ID == enabledId)
.AsEnumerable()
.Select(genericIngredient => GenericIngredientToViewModelWithUnitLabel(genericIngredient, languageId))
.Join(db.INGREDIENTS,
gi => gi.Id,
i => i.GENERIC_INGREDIENT_ID,
(i, gi) => new { GENERIC_INGREDIENTS = gi, INGREDIENTS = i })
.OrderBy(genericIngredient => genericIngredient.Name)
的GenericIngredientToViewModelWithUnitLabel如下:
public GenericIngredientsViewModel GenericIngredientToViewModelWithUnitLabel(GENERIC_INGREDIENTS genericIngredient, int languageId = 0)
{
DBEntities db = new DBEntities();
var genericIngredientTranslation = ReadGenericIngredientsTranslation(genericIngredient, languageId);
var unitLabelTranslation = UnitLabelsService.Service.ReadUnitLabelTranslationById(db, genericIngredient.UNIT_LABEL_ID, languageId);
return new GenericIngredientsViewModel
{
Id = genericIngredient.GENERIC_INGREDIENT_ID,
StatusCodeId = genericIngredient.STATUS_CODE_ID,
UnitLabelId = genericIngredient.UNIT_LABEL_ID,
Name = genericIngredientTranslation.GENERIC_INGREDIENT_NAME + " (" + unitLabelTranslation.Name+ ")",
Description = genericIngredientTranslation.GENERIC_INGREDIENT_DESCRIPTION,
Languages = genericIngredient.GENERIC_INGREDIENTS_TRANSLATIONS.Select(translation => translation.LANGUAGE_ID).ToList()
};
}
在這第二個查詢將返回一個錯誤「匿名類型:主料GENERIC_INGREDIENTS ,GenericIngredientsViewModel不包含名稱的定義。「。由於GenericIngredientToViewModelWithUnitLabel返回名稱,所以這對我來說沒有多大意義。此查詢必須返回一個IEnumerable。
感謝您的任何幫助。
那不要工作:(。同樣的錯誤 –
@DanielSerrão上面提到的現有查詢是否工作?如果是這樣,那麼根據查詢'.Name'是你在最後命令的內容,它是屬性o你的'GenericIngredientsViewModel'類。根據你的錯誤文本,它看起來像最後一個order by子句不能訪問'.Name'屬性,因爲新創建的匿名類型沒有它,所以上面的答案應該工作。你可以嘗試省略'OrderBy'子句來確認錯誤是由於它嗎?此外如果可能的話分享確切的錯誤信息。 – degant