0

I have been attempting to create a mini project in asp.NET MVC4 that simulates a small gaming review website. There's nothing spectacular going on I just wanted to get a handle on different aspects of the tools and language.

Currently I was thinking of creating a database set to associate Genres to an ID so when I create a Game database set I can reference the games by related genres. I was using a Code first approach to create the models, but I'm not sure how to properly reference the genres that are stored within a virtual collection so that If I create a table based on Genre or a table based on Game that they will reference properly. I'm just learning this MVC approach so I apologize if my terminology is off.

public class GamingModels : DbContext
{
    public DbSet<Games> GameDb { get; set; }
    public DbSet<Genre> GenreDb { get; set; }

    public GamingModels()
        : base("DefaultConnection")
    { }


    public class Games {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Summary { get; set;}
        public int Rating { get; set; }
        public virtual ICollection<Genres> Genres { get; set; }
    }

    public class Genre {
        public int ID { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Games> Games { get; set; }
    }
}
NBeers
  • 411
  • 1
  • 6
  • 11
  • 1
    [Started to write an answer but this is better][1] [1]: http://stackoverflow.com/questions/7050404/create-code-first-many-to-many-with-additional-fields-in-association-table – Nogusta Dec 09 '13 at 00:21
  • You might consider a Model First approach too. Code First is nice to have all your "source code" in one place including the database schemas but many things that are trivial when creating your database first become rather complex and even esoteric with a code first approach. Create your databases, use Entity Framework to render the DAL layer and off you go. For tracking development database changes that must go to production, consider using Red Gates Sql Compare tool, worth every bit of the 300 a license costs. – Brian Ogden Dec 09 '13 at 00:37

1 Answers1

1

Do you have an intermediate table to map games and genres? If not, you can try this approach:

Override the OnModelCreating method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Games>().HasMany(x=> x.Genres)
        .WithMany(x => x.Games)
        .Map(x => x.MapLeftKey("ID").MapRightKey("ID").ToTable("Genre"));
    modelBuilder.Entity<Genre>().HasMany(x => x.Games)
        .WithMany(x => x.Genres)
        .Map(x => x.MapLeftKey("ID").MapRightKey("ID").ToTable("Games"));
}

If you have a table that resolves many-to-many then follow Nogusta's recommendation.

Rowan Freeman
  • 15,724
  • 11
  • 69
  • 100