我无法弄清楚我在这里做错了什么。 MVC的新手和Entity的新手,所以我知道这让我退缩了。任何时候我打电话给AuthUser,AuthRole总是什么都没有,所以我最终做了类似的事情:
authuser.AuthRole = db.AuthRoleSet.Find(2) 'AuthRoleID of 2 = User
这对我来说很笨拙。如何让我的财产真正获得用户的角色?
这是我的班级结构: 公共类AuthUser '全球类 Dim db As New AuthUserContext
'Properties
Public Property AuthUserID() As Integer
<Required()> _
<Display(Name:="User Name")> _
<DomainUserValidation()> _
Public Property UserName() As String
<Display(Name:="Current Role")> _
Public Property AuthRole As AuthRole
End Class
Public Class AuthRole
Public Property AuthRoleID() As Integer
<Required()> _
<Display(Name:="Role Name")> _
Public Property RoleName() As String
<Required()> _
<Display(Name:="Is Administrator")> _
Public Property isAdministrator() As Boolean
<Required()> _
<Display(Name:="Is Active")> _
Public Property isActive() As Boolean
<Required()> _
Public Property AuthUser As ICollection(Of AuthUser)
End Class
Public Class AuthUserContext
Inherits DbContext
Public Property AuthUserSet() As DbSet(Of AuthUser)
Public Property AuthRoleSet() As DbSet(Of AuthRole)
End Class
答案 0 :(得分:1)
您有2个选项(抱歉c#语法):
1 - 在您需要时延迟加载AuthRole
- 为此,您的AuthRole
属性需要声明为virtual
public virtual AuthRole {get;set;}
现在,当您尝试访问AuthRole
时,EF会从数据库中获取它。
为此,您需要DbContext.Configuration.LazyLoadEnabled = true
另一种选择是通过使用如下查询来急切加载它:
var myUserWithRole = myContext.AuthUsers.Include("AuthRole").FirstOrDefault(x=>x.Id == userId);
这将从数据库中获取用户和角色。