我并不习惯使用VB.NET,但是我发现了谷歌搜索不足的错误。我已经创建了这个数据访问类,它有一个方法可以使用Yield
和vb.net的对象初始化快捷方式
Public Class FMACMarketingRepository
Private cvConnection As SqlConnection
Private cvCommand As SqlCommand
Private cvReader As SqlDataReader
Public Sub New(Role As InfotelLibrary.Data.DatabaseRole)
cvConnection = New SqlConnection(InfotelLibrary.Data.ConnectionString(Role, InfotelLibrary.Data.DatabaseName.Mongoose))
End Sub
Public Iterator Function GetAllFrontPageBanners() As IEnumerable(Of FrontPageBanner)
Using dbConnection As IDbConnection = cvConnection
Using cmd As IDbCommand = dbConnection.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sel_AllFmacFrontPageBanners"
Using reader As IDataReader = cmd.ExecuteReader()
If reader Is Nothing Then
Yield Nothing
End If
While reader.Read()
Yield New FrontPageBanner() With
{
.Banner_Id = CType(reader("Banner_ID"), Integer),
.Geo_Id = CType(reader("Geo_ID"), Long),
.Title = CType(reader("Title"), String),
.Description = CType(reader("Description"), String),
.Link = CType(reader("Link"), String),
.Image = CType(reader("Image"), Byte()),
.SpecialOffer = CType(reader("Special_Offer"), Boolean)
}
End While
End Using
End Using
End Using
End Function
End Class
Intellisense中有0个错误,它会构建,但是当我运行网页时会出现错误
System.InvalidCastException:无法转换类型' VB $ StateMachine_4_GetAllFrontPageBanners'输入' System.Collections.Generic.List`1 [InfotelData.Mongoose.Data.FrontPageBanner]'。
Line 7:
Line 8: Protected Sub Page_Load(ByVal sender As Object, e As EventArgs) Handles Me.Load
Line 9: Dim banners As List(Of FrontPageBanner) = cvRepo.GetAllFrontPageBanners()
Line 10: If banners.Count() > 0 Then
Line 11: rptUploadedBanners.DataSource = banners
调试只会在遇到page_load时出现相同的错误。
我认为应该责备用户错误。
答案 0 :(得分:2)
GetAllFrontPageBanners
会返回IEnumerable(Of FrontPageBanner)
(*) ,您正试图将其存储在List(Of FrontPageBanner)
中。我很惊讶它没有给出编译时错误(你可能处于Option Strict Off模式)
您需要使用.ToList从可枚举中创建一个列表,例如:
Dim banners As List(Of FrontBanner) = cvRepo.GetAllFrontPageBanners.ToList
(*) Iterator块内部将函数转换为生成的“class-state-machine”(实现IEnumerable(Of FrontBanner) )在你的情况下) 这是你得到的奇怪的名字,但你可以(并且应该)将它视为源代码中给出的返回类型 有关here
的更多信息