无法在MVC中获取一对一相关数据中的数据

时间:2015-05-28 13:48:32

标签: asp.net-mvc entity-framework-6

我无法获取中心位置,因为我可以保存并更新数据库。它只是在我遇到问题的地方取得

public class Club
{
    public Club()
    {
        this.Memberships = new HashSet<Membership>();
        this.People = new HashSet<Manager>();
        this.Center = new Center();
    }

    public int ClubId { get; set; }
    public string ClubName { get; set; }
    public System.DateTime OpenDate { get; set; }
    [ForeignKey("Center")]
    public virtual Center Center { get; set; }
    public virtual ICollection<Membership> Memberships { get; set; }
    public virtual ICollection<Manager> People { get; set; }

} 

我的中心模特

public class Center
{       
    [Key,ForeignKey("Club")]
    public int ClubId { get; set; }
    public string Location { get; set; }
    public virtual Club Club { get; set; }
}

,索引方法是

 public ActionResult Index()
    {
        return View(db.Clubs.ToList());
    }

1 个答案:

答案 0 :(得分:0)

您对Center的引用是虚拟的,因此它是延迟加载的。试试这个:

return View(db.Clubs.Include(c => c.Center).ToList());

https://msdn.microsoft.com/en-us/data/jj574232.aspx#lazy

我注意到您正在将实体模型发送到视图中。您可能希望查看viewmodel模式和automapper。 http://www.stevefenton.co.uk/Content/Blog/Date/201303/Blog/Why-You-Never-Expose-Your-Domain-Model-As-Your-MVC-Model/