Vb.net 使用实体框架更新表
我试图使用以下实体框架代码更新表中的字段,但它似乎不会修改字段。这真是令人沮丧,所以我想知道是否有人能告诉我我做错了什么 default.aspx.vb:Vb.net 使用实体框架更新表,vb.net,entity-framework,Vb.net,Entity Framework,我试图使用以下实体框架代码更新表中的字段,但它似乎不会修改字段。这真是令人沮丧,所以我想知道是否有人能告诉我我做错了什么 default.aspx.vb: Protected Sub btn_Save_Click(sender As Object, e As System.EventArgs) Handles btn_Save.Click SaveNewsBox() End Sub Private Sub GetNewsBox() Dim
Protected Sub btn_Save_Click(sender As Object, e As System.EventArgs) Handles btn_Save.Click
SaveNewsBox()
End Sub
Private Sub GetNewsBox()
Dim newsBox As GLC.Home = BLL.Homes.Homes.GetNewsBox()
If newsBox IsNot Nothing Then
txt_NewsBox.Text = newsBox.NewsBox
End If
End Sub
Private Sub SaveNewsBox()
Dim newsBox As New GLC.Home
newsBox.NewsBox = txt_NewsBox.Text
If BLL.Homes.Homes.Update(newsBox) Then
Master.AlertStyle = "alert-success"
Master.AlertMessage = "<i class=""fa fa-thumbs-o-up""></i> Meal details saved, <a href=""/secure/"">return to main menu.</a>"
Master.AlertVisible = True
Else
Master.AlertStyle = "alert-danger"
Master.AlertMessage = "<i class=""fa fa-thumbs-o-down""></i> Warning news box details could not be saved.</a>"
Master.AlertVisible = True
End If
End Sub
End Class
HomesHandler.vb:
Imports GLC
Imports System.Linq.Dynamic
Namespace MethodClasses
Public Class HomesHandler
Public Shared Function GetNewsBox() As Home
Using context As New GLCContext
Try
Return context.Homes.Single()
Catch ex As Exception
Return Nothing
End Try
End Using
End Function
Public Shared Function Update(newsBox As Home) As Boolean
Dim newsBoxUpdated As Boolean = False
Using context As New GLCContext
Try
context.Homes.Attach(newsBox)
Dim entry = context.Entry(newsBox)
entry.State = EntityState.Modified
context.SaveChanges()
newsBoxUpdated = True
Catch ex As Exception
newsBoxUpdated = False
End Try
End Using
Return newsBoxUpdated
End Function
End Class
End Namespace
我猜想,当您调用Dim entry=context.EntrynewsBox时,它会抛出一个异常并返回false,因为这个对象是您在aspx中创建的新对象,它找不到它 表中似乎只有一个条目,或者您只提供了获取第一行的方法。如果是这样,我会这样做:
Public Shared Function Update(newsBox As Home) As Boolean
Dim newsBoxUpdated As Boolean = False
Using context As New GLCContext
Try
Dim entry = GetNewsBox()
entry.NewsBox = newsBox.NewsBox
context.SaveChanges()
newsBoxUpdated = True
Catch ex As Exception
newsBoxUpdated = False
End Try
End Using
Return newsBoxUpdated
End Function
上下文将知道该实体已被修改,因为您在附加该实体时对其进行了更改。如果调用Attach时没有键或EF用某种方法来标识具有特定行的给定对象,那么它最终将插入新行,但您可能永远也看不到它,因为您只得到一行
如果这确实是您修改的唯一属性,您可以通过简单地将文本框的值作为字符串传递到更新函数中,而不是传递一个新的空字段对象,从而节省一些开销并使其更简单。没有错误?至少,您似乎没有为newsBox提供PK值,或者该值始终等于0。如果从更新函数中删除try/catch,是否会出现错误?另外,您是否能够共享您的模式?
Public Shared Function Update(newsBox As Home) As Boolean
Dim newsBoxUpdated As Boolean = False
Using context As New GLCContext
Try
Dim entry = GetNewsBox()
entry.NewsBox = newsBox.NewsBox
context.SaveChanges()
newsBoxUpdated = True
Catch ex As Exception
newsBoxUpdated = False
End Try
End Using
Return newsBoxUpdated
End Function