【问题标题】:Code First Entity / MVC4 - why aren't my models hydrated?Code First Entity / MVC4 - 为什么我的模型没有水合?
【发布时间】:2014-08-18 23:57:01
【问题描述】:

我无法弄清楚我在这里做错了什么。 MVC 新手和 Entity 新手,所以我知道这阻碍了我。每当我调用 AuthUser 时,AuthRole 总是什么都不是,所以我最终会执行以下操作:

authuser.AuthRole = db.AuthRoleSet.Find(2) 'AuthRoleID of 2 = User

这对我来说只是感觉很笨拙。如何让我的属性真正获得用户的角色?

这是我的班级结构: 公共类 AuthUser '类全局变量 将数据库调暗为新的 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

【问题讨论】:

    标签: asp.net-mvc vb.net asp.net-mvc-4 entity code-first


    【解决方案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);
    

    这将从数据库中获取用户和角色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      相关资源
      最近更新 更多