我正在为使用 Entity Framework 5 作为后端数据源的新应用程序构建存储库。我有适用于简单模型的基本 CRUD 操作,但我很难理解如何在更新现有对象时更新相关对象。
模型
导入系统导入 System.Collections.Generic
Partial Public Class tblUser
Public Property idUser As Integer
Public Property username As String
Public Property pwd As String
Public Overridable Property tblUsermmRoles As ICollection(Of tblUsermmRole) = New HashSet(Of tblUsermmRole)
End Class
Imports System
Imports System.Collections.Generic
Partial Public Class tblUsermmRole
Public Property idUser As Integer
Public Property idRole As Integer
Public Overridable Property tblUser As tblUser
Public Overridable Property tblUserRole As tblUserRole
End Class
我正在尝试针对相关的 tblUser 记录将记录添加到 tblUsermmRole 对象,但我无法使更新正常工作。
POCO
Public Class User
Public Property ID As Int32
Public Property Username As String
Public Property Password As String
Public Property AccessRoles As IEnumerable(Of Int32)
Public Sub New()
End Sub
Public Sub New(id As Int32, userName As String, password As String, roles As List(Of Int32))
Me.ID = id
Me.Username = userName
Me.Password = password
Me.AccessRoles = roles
End Sub
End Class
Public Class UserRoles
Public Property RoleID As Int32
Public Sub New(roleID As Int32)
Me.RoleID = roleID
End Sub
End Class
存储库
Imports System.Data.Entity
Namespace DataAccess.Repository
Public MustInherit Class EntityFramworkContextBase
Inherits DbContext
Implements IUnitOfWork
Public Sub New(entityConnectionStringOrName As String)
MyBase.New(entityConnectionStringOrName)
End Sub
Public Sub Add(Of T As Class)(obj As T) Implements IUnitOfWork.Add
[Set](Of T).Add(obj)
End Sub
Public Sub Attach(Of T As Class)(obj As T) Implements IUnitOfWork.Attach
Dim entity As T
If ExistsInContext(obj) Then
entity = ObjectInContext(obj)
Entry(entity).CurrentValues.SetValues(obj)
Else
entity = [Set](Of T).Attach(obj)
End If
Entry(entity).State = EntityState.Modified
End Sub
Public Sub Commit() Implements IUnitOfWork.Commit
MyBase.SaveChanges()
End Sub
Public Function [Get](Of T As Class)() As IQueryable(Of T) Implements IUnitOfWork.Get
Return [Set](Of T)()
End Function
Public Function Remove(Of T As Class)(obj As T) As Boolean Implements IUnitOfWork.Remove
Dim entity As T
If ExistsInContext(obj) Then
entity = ObjectInContext(obj)
Else
entity = [Set](Of T).Attach(obj)
End If
[Set](Of T).Remove(entity)
Return True
End Function
Private Function ExistsInContext(Of T As Class)(obj As T) As Boolean
Return [Set](Of T).Local.Any(Function(o) o.Equals(obj))
End Function
Private Function ObjectInContext(Of T As Class)(obj As T) As T
Return [Set](Of T).Local.FirstOrDefault(Function(o) o.Equals(obj))
End Function
End Class
End Namespace
问题
在方法中调用该Entry(entity).CurrentValues.SetValues(obj)
行时,Attach
会复制基本属性,但不会复制 tblUsermmRole 对象的新元素。
更新后的新对象
SetValues 之后的实体
从最初的研究来看,该方法似乎没有复制本文中讨论的SetValues
相关导航属性
问题
鉴于我正在使用的存储库模式(加上 UnitOfWork 模式),您如何维护对象图关系并更新数据库?
附加说明
对于带有附加 tblUsermmRoles 的 tblUsers 对象的新实例,此方法按预期工作。添加两个表的记录以维护外键。