1
我想用EF Code-First將這些類添加到數據庫中。填充對象並嘗試填充上下文「dbContext.Tracks.Add(t1)」後。我收到錯誤「無法投射'System.Collections.Generic.HashSet`1 [Vinyl7]'類型的對象鍵入'Vinyl7'」任何人都可以指出我失蹤了什麼?無法投射「System.Collections.Generic.HashSet」類型的對象
Public Class Vinyl7
<Key>
Public Overridable Property mediaId As Long
Public Overridable Property parentMediaId As System.Nullable(Of Long)
Public Overridable Property side As String
<ForeignKey("mediaId"), Required>
Public Overridable Property track As Track
End Class
Public Class Track
<Key>
Public Property mediaId As Long
Public Property title As String
Public Overridable Property Vinyl7T As ICollection(Of Vinyl7) = New HashSet(Of Vinyl7)
End Class
這是我的上下文
Public Class MediaRepo : Inherits DbContext
Public Sub New()
MyBase.New("name=MediaDB")
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
End Sub
Public Property Vinyl7s As DbSet(Of Vinyl7)
Public Property Tracks As DbSet(Of Track)
End Class
這是我的方法。
Using db = New MediaRepo
Dim t1 = New Track
t1.title = "Kutchie"
Dim t2 = New Track
t2.title = "Drug Trade"
Dim a = New Media.Vinyl7
a.side = "A"
a.parentMediaId = t1.mediaId
a.track = t1
Dim b = New Media.Vinyl7
b.side = "B"
b.parentMediaId = t1.mediaId
b.track = t2
t1.Vinyl7T.Add(a)
t1.Vinyl7T.Add(b)
db.Tracks.Add(t1)
SaveChanges(db)
End Using
因爲我已經更新了,但仍押注錯誤'code' 公共屬性可覆蓋的軌道作爲軌道 –
ruffone
2013-03-07 04:08:09
我寫了一個testapp這就是你的模型工作。也許你可以看到你的代碼有什麼不同?嘗試創建一個控制檯應用程序並粘貼我的代碼,它會創建數據庫並能夠插入一些實體 – 2013-03-07 04:12:29
感謝馬克,這已經讓我有了一種方式'。如果允許我的話。我如何製作我認爲Track_trackId和Vinyl7_mediaId之間的一對一關係我希望能夠在不添加乙烯基的情況下添加曲目 – ruffone 2013-03-07 08:46:50