【发布时间】:2014-09-14 17:04:32
【问题描述】:
当只有类别要返回时,我的以下查询工作正常,但只要有多个类别,我就会收到 Sequence contains more than one element 错误消息。我想返回所有相关类别。因此,我将 DTO 中的 PostCategory 从字符串更改为列表,这就是我收到转换错误的时候。我还尝试将其更改为IList(of String) 和IList(of be_Category),并将ToList 添加到ca.CategoryName。那没有用。
我的连接查询:
Public Function SelectByID(id As Integer) As PostDTO Implements IPostRepository.SelectByID
Dim post As New PostDTO
Using db As Ctx = New Ctx
post = From ca In db.be_Categories
Join c In db.be_PostCategory On ca.CategoryID Equals (c.CategoryID)
Join p In db.be_Posts On c.PostID Equals (p.PostID)
Where p.PostRowID = id
Select New PostDTO With {
.PostCategory = ca.CategoryName,
.PostDateCreated = p.DateCreated,
.PostGuid = p.PostID,
.PostId = p.PostRowID,
.PostText = p.PostContent,
.PostTitle = p.Title}).Single
End Using
Return post
End Function
那么是否可以将类别名称序列投影到新的 DTO 或其他东西中,或者是否有其他方法可以返回所有类别?我猜由于 CategoryName 是一个字符串,L2E 无法将字符串投影到列表中。我需要GroupBy 将类别字符串投影到新表单中吗?我也试过AsEnumerable 和String.Join - 都没有成功。
DTO 在下方 - 如果 PostCategory 是一个字符串,那么我可以将单个类别返回到视图中。我希望我已经解释清楚了。
Public Class PostDTO
Public PostId As Integer
Public PostGuid As Guid
Public PostTitle As String
Public PostSummary As String
Public PostText As String
Public PostDateCreated As DateTime
Public PostIsPublished As Boolean
Public PostCategory As IList(Of be_PostCategory)
End Class
编辑: 更新 SelectById:
Public Function SelectByID(id As Integer) As IEnumerable(Of PostDTO) Implements IPostRepository.SelectByID
Dim post As IEnumerable(Of PostDTO)
Using db As Ctx = New Ctx
post = From ca In db.be_Categories
Join c In db.be_PostCategory On ca.CategoryID Equals (c.CategoryID)
Join p In db.be_Posts On c.PostID Equals (p.PostID)
Where p.PostRowID = id
Select New PostDTO With {
.PostCategory = ca.CategoryName,
.PostDateCreated = p.DateCreated,
.PostGuid = p.PostID,
.PostId = p.PostRowID,
.PostText = p.PostContent,
.PostTitle = p.Title}).ToList
End Using
End Function
【问题讨论】:
标签: vb.net join asp.net-mvc-5 entity-framework-6.1