【问题标题】:How to reference an object in your view model using EF 4.1如何使用 EF 4.1 在视图模型中引用对象
【发布时间】:2011-09-14 10:30:29
【问题描述】:

我正在使用ASP.NET MVC 3Entity Framework 4.1 code first

我在我的数据库上下文类中定义了以下内容:

public class HefContext : DbContext
{
   public DbSet<GrantApplication> GrantApplications { get; set; }
   public DbSet<MaritalStatusType> MaritalStatusTypes { get; set; }
}

我的 MaritalStatusType 类:

public class MaritalStatusType : IEntity
{
   public int Id { get; set; }
   public string Name { get; set; }
   public bool IsActive { get; set; }
}

在我的视图模型中,我有以下内容:

public class GrantApplicationDetailsViewModel
{
   public int MaritalStatusTypeId { get; set; }
   public MaritalStatusType MaritalStatusType { get; set; }
}

查看代码显示婚姻状况类型名称:

<tr>
   <td><label>Marital Status:</label></td>
   <td>@Model.MaritalStatusType.Name</td>
</tr>

在我的控制器的操作方法中,我通过 id 获取授权应用程序对象。它具有来自授权申请表的婚姻状况类型 ID。然后我将授权应用程序对象映射到我的 GrantApplicationDetailsViewModel。没关系。但是当我想在我的视图中指定婚姻状态类型的名称时,它会给我错误,object not set to an instance of an object。我该如何让它发挥作用?

【问题讨论】:

标签: c# entity-framework asp.net-mvc-3 entity-framework-4 entity-framework-4.1


【解决方案1】:

我刚刚在我的授权应用程序对象中添加了虚拟属性,现在它似乎工作得很好。

public class GrantApplication : IEntity
{
   public int Id { get; set; }

   public int MaritalStatusTypeId { get; set; }
   public virtual MaritalStatusType MaritalStatusType { get; set; }
}

【讨论】:

  • 是的,从我听到的建议将所有变量虚拟化。这是为 EF 设计的。
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多