简体   繁体   English

实体框架,如何在WHERE中使用对象查询,以及如何检索实体记录

[英]entity framework, how to use object query with a WHERE, AND to retrieve entity record

I am trying to add and AND condition to my entity framework where clause, but the way I am doing it is not working. 我正在尝试向我的实体框架where子句添加AND条件,但是我这样做的方式不起作用。 Can anyone show me how to do this the correct way please? 谁能告诉我如何正确执行此操作? Before adding the AND condition, the code worked fine. 在添加AND条件之前,代码可以正常工作。

Dim myRecipeStepsHistory = myContext.RefineRecipeStep.Where("it.Recipe_Id=" & strRecipeId And "it.IngredientItemNumber=" & strIngredientNumber).FirstOrDefault()

The error I get reads as: 我得到的错误为:

Conversion from string "it.Recipe_Id=11" to type 'Long' is not valid. 从字符串“ it.Recipe_Id = 11”到类型“ Long”的转换无效。

Thank you very much. 非常感谢你。

I would try to use the built in linq if you can. 如果可以的话,我将尝试使用内置的linq。 It will check your values at compile time for you and you won't get nasty surprises at run time. 它将在编译时检查您的值,并且在运行时不会给您带来讨厌的惊喜。 You can use magic-strings of course but why not use one of the best features of of an ORM? 您当然可以使用魔术字符串,但为什么不使用ORM的最佳功能之一呢? Imagine updating a tables field type, the compiler will automatically let you know every place you need to update your code. 想象一下更新表字段类型,编译器将自动让您知道更新代码所需的每个位置。 Instead of having forgetting about one and then having it crash here and there. 而不是忘记一个,然后使它在这里和那里崩溃。

If you're querying a single table, often it's easier to put the 'wheres' inside the FirstOrDefault(); 如果要查询单个表,通常将“ wheres”放在FirstOrDefault()内会更容易;

Dim myRecipeStepsHistory = 

myContext.RefineRecipeStep
         .FirstOrDefault(x => x.Recipe_Id.Equals(strRecipeId) &&
                              x.IngredientItemNumber == strIngredientNumber);

if(myRecipeStepHistory != null)
{
     // 
}

You may have to cast your values so it matches the correct data type for Recipe_Id and IngredientItemNumber. 您可能必须强制转换值,使其与Recipe_Id和IngredientItemNumber的正确数据类型匹配。

可能是缺少空格和/或放错了“”:

Dim myRecipeStepsHistory = myContext.RefineRecipeStep.Where("it.Recipe_Id=" & strRecipeId.ToString() & " And it.IngredientItemNumber=" & strIngredientNumber.ToString()).FirstOrDefault() 

Presumably, if you are using EF, your model already knows about RefineRecipeStep, and thus you shouldn't be writing sql in place like that? 大概,如果您使用的是EF,则您的模型已经知道RefineRecipeStep,因此您不应该像这样编写sql吗?

Thus what you want becomes something more like: 因此,您想要的东西变得更像:

Dim myRecipeStepsHistory = myContext.RefineRecipeStep
  .Where((it) => it.Recipe_Id.Equals(recipeId))
  .Where((it) => it.IngredientItemNumber.Equals(ingredientNumber))
  .FirstOrDefault()

or possibly: 或可能:

Dim myRecipeStepsHistory = myContext.RefineRecipeStep
  .Where((it) => it.Recipe.Id.Equals(recipeId))
  .Where((it) => it.IngredientItemNumber.Equals(ingredientNumber))
  .FirstOrDefault()

if recipe is a known relationship... 如果配方是已知的关系...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM