无法使用Repository Pattern和LINQ to SQL更新数据库

时间:2010-06-28 18:14:41

标签: asp.net-mvc linq repository

我的项目有以下设置

  

控制器 - > 服务(用于验证) - > 存储库(对于LINQ) - > dbml - >的数据库

控制器

''# <AcceptVerbs(HttpVerbs.Post)>  -  hiding this line so that code formatting looks proper in SO.
Function Edit(ByVal user As Domain.User, ByVal id As Integer) As ActionResult

    If ModelState.IsValid Then

        If Not String.IsNullOrEmpty(user.UserName) AndAlso _
            Not String.IsNullOrEmpty(user.WebSite) AndAlso _
            Not String.IsNullOrEmpty(user.Email) AndAlso _
            Not String.IsNullOrEmpty(user.About) AndAlso _
            Not user.Region Is Nothing AndAlso _
            Not user.BirthDate Is Nothing AndAlso _
            Not user.isProfileComplete = True Then

            user.isProfileComplete = True
            user.Reputation = user.Reputation + 10

            UserService.UpdateUser(user)

        Else
            UserService.UpdateUser(user)
        End If

        UserService.SubmitChanges()

        Return RedirectToAction("Details", "Users", New With {.id = id, .slug = user.UserName})
    Else
        Return View(user)
    End If
End Function

服务

    Public Sub UpdateUser(ByVal user As User) Implements IUserService.UpdateUser
        _UserRepository.UpdateUser(user)
    End Sub

    Public Sub SubmitChanges() Implements IUserService.SubmitChanges
        _UserRepository.SubmitChanges()
    End Sub

存储库

    Public Sub UpdateUser(ByVal user As User) Implements IUserRepository.UpdateUser
        Dim _user = (From u In dc.Users
            Where u.ID = user.ID
            Select u).Single
        _user = user
    End Sub

    Public Sub SubmitChanges() Implements IUserRepository.SubmitChanges
        dc.SubmitChanges()
    End Sub

问题在于它没有得到更新。我必须在这里做一些非常愚蠢的事情。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

Public Sub UpdateUser(ByVal user As User) Implements IUserRepository.UpdateUser 
    Dim _user = (From u In dc.Users 
        Where u.ID = user.ID 
        Select u).Single 
    _user = user 
End Sub 

在此方法中,您将从数据库中获取用户。在了解属性是否已更改方面,Linq2Sql正在跟踪该用户实例。因此,在linq语句之后_user被数据上下文知道并且可以被跟踪。将用户参数分配给对象(_user = user)时,将丢失对跟踪对象的引用,并将其替换为未跟踪的对象。您可以单独更新包含数据库信息的_user变量,也可以尝试将user参数附加到数据上下文并直接使用(dc.Users.Attach(user))。附加可能很复杂,因为如果您没有相同的datacontext实例,那么它将无法正确附加。以下是我将如何做到这一点。

Public Sub UpdateUser(ByVal user As User) Implements IUserRepository.UpdateUser 
    Dim _user = (From u In dc.Users 
        Where u.ID = user.ID 
        Select u).Single 
    With _user
        .Name = user.Name
        .Email = user.Email
    End With
End Sub