简体   繁体   中英

ASP.net MVC Entity framework

I tried many things but I am facing problem in implementing the following in Entity Framework ASP.NET MVC. Please tell me step by step what should I do to implement the controllers and views. I am confused how to implement many to many relationship between club and manager

Manager model

public class Manager:Person
{
        public Manager()
        {
            Clubs = new HashSet<Club>();
        }
        public string AssignedDuty { get; set; }
        public System.DateTime AssignedDate { get; set; }
        public virtual ICollection<Club> Clubs { get; set; }
}

Club model

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

    public int ClubId { get; set; }
    public string ClubName { get; set; }
    public System.DateTime OpenDate { get; set; }


    public virtual Center Center { get; set; }
    public virtual ICollection<Membership> Memberships { get; set; }

    public virtual ICollection<Manager> People { get; set; }

}

Many-to-many relationships are defined using a junction table. As for how Controllers are implemented, try this: http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-a-controller-cs

Your Models as in Model-View-Controller should not be concerned on how the manager is linked to the club in the database. The should just be concerned that they are related not how .

I would do it like this:

  • In your DB/EntityFramework, use a junction table as explained and linked to Juann Strauss
  • When you load data from database (as in the OnModelCreating event) you populate the relation

Here is a blog post that seems to explain what you are trying to accomplish: http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

Finally its working now I only have to add few lines to my controller. and my Final Assign Club looks like this and its working perfectly

[HttpPost, ActionName("AssignClub")]
public ActionResult AssignClub(AssignClubVM ac)
{
        Manager m = db.Managers.Find(ac.manager.PersonId);
        foreach (var clubid in ac.SelectedClubs)
        {
            m.Clubs.Add(db.Clubs.Find(clubid));
        }
        db.SaveChanges();
        return RedirectToAction("Index");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM