vendredi 6 mai 2016

MVC EF Adding object to database

So this is a continuation of the question here

I am trying this below:

public DbSet<User> Users { get; set; }
public DbSet<Sport> Sports { get; set; }
public DbSet<Team> Teams { get; set; }

  • I can have many Sports
  • I can have many Teams in a Sport
  • I can have many Teams in a User
  • I can have many Users in a Team

Sport

public int ID { get; set; }
public List<Team> Teams { get; set; }

Team

public Team(int ID, int SportID, int Wins, int Losses, String Name, String Description, double Reputation, List<User> Members, byte[] TeamLogo)
 {
     this.ID = ID;
     this.SportID = SportID;
     this.Wins = Wins;
     this.Losses = Losses;
     this.Name = Name;
     this.Description = Description;
     this.Reputation = Reputation;
     this.Members = Members;
     this.TeamLogo = TeamLogo;
 }
public int ID { get; set; }
public List<User> Members { get; set; }
public int SportID { get; set; }

User

public int UserID { get; set; }
public List<Team> Teams { get; set; }

DB

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Adds middle table between Users and Teams
        modelBuilder.Entity<User>()
            .HasMany<Team>(t => t.Teams)
            .WithMany(m => m.Members)
            .Map(w => w.ToTable("UserTeam")
                       .MapLeftKey("UserID")
                       .MapRightKey("TeamID"));
    }

public void addTeam(Team team, String sport)
    {
        // Add the team to the correct sport
        Teams.Add(team);
        this.SaveChanges();
    }

Controller

model.NewTeam = new Team(0, db.getSportID(model.SelectedSport), 0, 0, model.TeamName, model.TeamDescription,
                   100, new List<User>() { model.currentUser }, model.ActualImage);
db.addTeam(model.NewTeam, model.SelectedSport);

Issue:

It adds a record to the Teams table just fine. It adds the record to the UserTeam table just fine. The problem is that it is also adding a new record to the User table as well so I have repeating users in my User table. Also, when I query the Teams Table, I get a null List Members so EF isn't properly getting the Members of each team from the Many-Many table.

Aucun commentaire:

Enregistrer un commentaire