我正在开发一个使用Entity Framework和MySql的winforms应用程序。我有两个实体类,一对多关系。
第1课:
Public Class Sinavsablon
Public Property Id As Integer
Public Property Isim As String
Public Overridable Property Dersler As ICollection(Of SablonDers)
'And some other irrelevant properties
End Class
第2课:
Public Class SablonDers
Public Property Id As Integer
Public Property Isim As String
Public Property Sablon As Sinavsablon
Public Property SablonId As Integer
'And some other irrelevant properties
End Class
我的dbcontext类:
Public Class OsbsContext
Inherits DbContext
Public Property SinavSablonlar As DbSet(Of Sinavsablon)
Public Property SablonDersler As DbSet(Of SablonDers)
Public Sub New(ByVal connection As System.Data.Common.DbConnection)
MyBase.New(connection, True)
End Sub
Protected Overrides Sub OnModelCreating(modelBuilder As System.Data.Entity.DbModelBuilder)
modelBuilder.Entity(Of Sinavsablon).ToTable("sinavsablonlari")
modelBuilder.Entity(Of SablonDers).ToTable("sablondersleri")
modelBuilder.Entity(Of SablonDers).HasRequired(Function(d) d.Sablon).WithMany(Function(s) s.Dersler) _
.HasForeignKey(Function(d) d.SablonId).WillCascadeOnDelete(True)
MyBase.OnModelCreating(modelBuilder)
End Sub
End Class
我的数据库表是:
Table sablondersleri
Columns:
Id(int)
Isim(varchar)
SablonId(int)
Table sinavsablonlari
Columns :
Id(int)
Isim(varchar)
And some other columns
当我尝试插入或删除SinavSablon类型的实体时,一切正常。但是当我尝试更新它时会抛出以下异常。
Multiplicity constraint violated. The role 'SablonDers_Sablon_Target' of the relationship 'Öğrenci_Sınav_Bilgi_Sistemi.SablonDers_Sablon' has multiplicity 1 or 0..1.
以下是我用来更新记录的代码。
Using context as new OsbsContext(conn)
Dim sablonToUpdate = (From s In context.SinavSablonlar Where s.Id = GelenSablon.Id).First
With sablonToUpdate
.Isim = txtSablonIsim.Text
End With
sablontoDuzenle.Dersler.Clear()
For Each d As SablonDers In lstDersler.Items
sablontoDuzenle.Dersler.Add(d)
Next
context.SaveChanges()
End Using
如果我不更新childentity集合,一切正常。但是当我尝试使用列表框的内容更新childentity集合时,它会在context.SaveChanges()行上抛出异常。
我一直试图找到解决方案好几天,我通过互联网查看了几乎关于这个问题的每个主题,但找不到解决方案。希望能在这里找到答案。
谢谢。