【发布时间】:2015-01-03 12:24:09
【问题描述】:
我决定第一次使用 Entity Framework 6.0。所以是的,我对此很陌生。 与往常一样,我首先创建了数据库,然后生成了 Code First 模型(通过 Visual Studio 向导),如下所示:
Partial Public Class DataContext
Inherits DbContext
Public Sub New()
MyBase.New("name=DataContext")
End Sub
Shared Sub New()
DbInterception.Add(New FullTextInterceptor())
End Sub
Public Overridable Property StatusInfoes As DbSet(Of StatusInfo)
Public Overridable Property UpdateSets As DbSet(Of UpdateSet)
Public Overridable Property Users As DbSet(Of User)
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder)
modelBuilder.Configurations.Add(New UpdateSetFtsMap)
modelBuilder.Entity(Of StatusInfo)() _
.Property(Function(e) e.Information) _
.IsUnicode(False)
modelBuilder.Entity(Of UpdateSet)() _
.Property(Function(e) e.Title) _
.IsUnicode(False)
modelBuilder.Entity(Of UpdateSet)() _
.Property(Function(e) e.Files) _
.IsUnicode(False)
modelBuilder.Entity(Of UpdateSet)() _
.HasMany(Function(e) e.StatusInfoes) _
.WithRequired(Function(e) e.UpdateSet) _
.WillCascadeOnDelete(False)
modelBuilder.Entity(Of User)() _
.Property(Function(e) e.Login) _
.IsUnicode(False)
modelBuilder.Entity(Of User)() _
.Property(Function(e) e.Password) _
.IsUnicode(False)
modelBuilder.Entity(Of User)() _
.Property(Function(e) e.Surname) _
.IsUnicode(False)
modelBuilder.Entity(Of User)() _
.Property(Function(e) e.Name) _
.IsUnicode(False)
modelBuilder.Entity(Of User)() _
.HasMany(Function(e) e.StatusInfoes) _
.WithRequired(Function(e) e.User) _
.WillCascadeOnDelete(False)
End Sub
Public Function GetServerDate() As DateTime
Return Database.SqlQuery(Of DateTime)("Select GetDate()").SingleOrDefault
End Function
End Class
所以我有一个 UpdateSet 对象,其中至少有一个 StatusInfo 对象。 到目前为止一切顺利。
奇怪的是删除。这是我的代码:
Public Function DeleteById(id As Integer) As Integer Implements IDataMapper(Of UpdateSetDataTransferObject).DeleteById
Dim result = -1
Using ctx As New DataContext
Dim dbUpdateSet = (From o In ctx.UpdateSets Where o.Id = id Select o).SingleOrDefault
If dbUpdateSet IsNot Nothing Then
ctx.UpdateSets.Remove(dbUpdateSet)
Try
ctx.SaveChanges()
result = 0
Catch ex As DbUpdateException
End Try
End If
End Using
Return result
End Function
奇怪的是,有时它会起作用。 (假设 20 个中有 1 个)。 通过调试,我观察到大多数情况下的代码
ctx.UpdateSets.Remove(dbUpdateSet)
从 StatusInfoes 集合中删除所有 StatusInfo 对象(子对象),因此我认为 EF 没有有关要删除的子对象的信息。所以我得到了错误:
DELETE 语句与 REFERENCE 约束“FK_UpdateSetStatus_UpdateSet”冲突。冲突发生在数据库“UpdateWizard”、表“dbo.StatusInfo”、列“UpdateSetId”中。 声明已终止。
正如我之前提到的,有时它会起作用。那些时候,StatusInfo 对象的集合没有被 remove 命令清除。
谁能帮忙?
【问题讨论】:
标签: c# vb.net entity-framework-6