我正在爲使用實體框架5作爲後端數據源的新應用程序構建存儲庫。我有簡單模型的基本CRUD操作,但我正在努力瞭解如何更新升級到升級對象的相關對象。使用實體框架的存儲庫模式5.更新相關對象
型號
進口系統 進口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
我試圖記錄添加到tblUsermmRole對象反對相關的tblUser記錄,但我無法使更新工作。
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
問題
在Attach
方法中調用Entry(entity).CurrentValues.SetValues(obj)
行時,將複製基本屬性,但tblUsermmRole對象的新元素不是。
與更新
實體新建對象setValues方法
從它看起來像在this post
討論的SetValues
方法不會對相關導航屬性複製最初的研究後,
問題
鑑於我正在使用的存儲庫模式(加上UnitOfWork模式),您如何維護對象圖關係並更新數據庫?
附加說明
此方法效果如預期的向tblUsers的新實例對象附有tblUsermmRoles。兩個表的記錄都添加了外鍵。