MVC4如何在没有导航属性的情况下加载相关数据

2024-05-06

我对 MVC 相当陌生,并且已经使用 EF-database-first 创建了一个 MVC4 应用程序。该数据库不包含外键定义,我无法添加它们(我不拥有该数据库)。以下是数据库中的两个示例类:

public partial class Allocation
{
    public int AllocID { get; set; }
    public int DeptID { get; set; }
    public decimal AllocationPercent { get; set; }
}

public partial class Department
{
    public int DeptID { get; set; }
    public string DeptName { get; set; }
    public string Account { get; set; }
}

默认分配索引页面显示部门 ID。我想显示部门名称。如果没有导航属性,我该如何做到这一点?

I tried

public class AllocationController : Controller
{
    private Entities db = new Entities();

    //
    // GET: /Allocation/

    public ActionResult Index()
    {
        return View(db.Allocation.Include(d => d.DeptID).ToList());
    }
...

但这会产生错误(“指定的包含路径无效。EntityType 'TESTModel.Allocation' 未声明名为 'DeptID' 的导航属性。”)...

我也不知道如何在没有导航属性的情况下编写急切加载或显式加载代码,这引发了这个问题。就效率而言,我认为加载相关信息的方式并不重要,因此任何方向的任何帮助将不胜感激。


数据库不必有定义,只要字段存在并且实体已放置在数据库中并考虑到引用完整性即可。您所需要做的就是让实体框架知道这种关系。这是通过virtual关键字创建“导航属性”。

public partial class Allocation
{
 public int AllocID { get; set; }
 public int DeptID { get; set; }
 public decimal AllocationPercent { get; set; }
 public virtual Department Department { get; set; } /* this is your nav property */
}

public partial class Department
{
 public int DeptID { get; set; }
 public string DeptName { get; set; }
 public string Account { get; set; }
}

现在你可以这样做:

db.Allocation.Include(a => a.Department).ToList()

可能会出现错误,要求您使用外键定义(尽管我不这么认为)。如果是这种情况,您将需要像这样装饰您的导航属性

[ForeignKey("DeptID")]
public virtual Department Department { get; set; }

您也可以尝试这样操作:

 public int AllocID { get; set; }
 [ForeignKey("Department")]
 public int DeptID { get; set; }
 public decimal AllocationPercent { get; set; }
 public virtual Department Department { get; set; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC4如何在没有导航属性的情况下加载相关数据 的相关文章

随机推荐