在 MVC 3 vb.net 中使用 EF 选择单行
我正在尝试使用以下代码行从 EF 数据库模型中获取单个值。
Dim _classRoom As classrm = db.classrms.Select(Function(b) b.Course_ID = _CurrCourse.course_ref)
其中 classrm 是实体的名称,而 db 被声明为新实体。我想做的是根据匹配的 Course_ID 从实体中选择一行,在该模型中是一个字符串。这样我以后就可以使用变量 _classRoom 从同一行中获取其他项目。但是我收到以下错误:
Unable to cast object of type 'System.Data.Objects.ObjectQuery`1[System.Boolean]' to type 'Trial_Online.classrm'.
有人有任何想法吗???我必须与几个不同的实体执行类似的任务,但如果我指向正确的方向,我可以从那里进行管理......
I am trying to get back a single from from a EF database model using the below line of code..
Dim _classRoom As classrm = db.classrms.Select(Function(b) b.Course_ID = _CurrCourse.course_ref)
Where classrm is the name of the entity and db is declared as a new entity. What I am trying to do is select a row from the entity based on matching Course_ID which in this model is a string. So that I can later use the variable _classRoom to get other items out of the same row.. However I am getting the following error:
Unable to cast object of type 'System.Data.Objects.ObjectQuery`1[System.Boolean]' to type 'Trial_Online.classrm'.
Anyone got any ideas??? I have to preform similar tasks with several different Entities but if I get pointed in the right direction I can manage from there...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
Where
而不是Select
来过滤结果,并在末尾添加First()
或Single()
:First()
和Single()
的区别在于Single()
如果数组中的元素超过 1 个,则会抛出异常结果。如果结果序列为空,两者都会抛出异常。如果没有结果,您还可以使用
FirstOrDefault()
和SingleOrDefault()
返回Nothing
。Use
Where
instead ofSelect
to filter the results, and addFirst()
orSingle()
to the end:The difference between
First()
andSingle()
is thatSingle()
will throw an exception if there is more than 1 element in the result. Both will throw an exception if the result sequence is empty.You can also use
FirstOrDefault()
andSingleOrDefault()
to returnNothing
if there are no results.不太熟悉 VB.NET 中的查询语法,但在 C# 中,我很确定您必须将
First()
或Single()
添加到查询末尾它将结果投影到对象实例中。否则我认为你会得到一个结果集(可能是一个 IQueryable 对象)。Not too familiar with query syntax in VB.NET, but in C# I'm pretty sure you have to add
First()
orSingle()
to the end of the query for it to project the result into an object instance. Otherwise I think you get a resultset (probably anIQueryable
object).