Solved

Seeding a join table in MVC

Posted on 2014-01-21
4
289 Views
Last Modified: 2014-01-22
Hi:

I have a database in MVC 5 that I am trying to seed.  The db consists of courses - each of which is made up of one or more modules.

Seeding the courses and modules works fine but I am having problems seeding the join-table course-modules - since at the time of seeding, there are no ids for either.

Here's my code - any suggestions on how to fix it greatly appreciated.

public class DatabaseInitializer :  DropCreateDatabaseIfModelChanges<DataContext>
{
	public override void Seed(DataContext context)
	{	
		public class Course 
		{
			public int Id { get; set; }
			public string Name { get; set; }
		}

		public class Module
		{
			public int Id { get; set; }
			public string Name { get; set; }
		}

		var course = new Course
		{
			Name = "Social Studies"
		};
		context.Courses.Add(course);

		var module = new Module
		{
			Name = "History",
		};
		context.AddModule(module)

		var module = new Module
		{
			Name = "Geography",
		};
		context.AddModule(module)
		
		//Problem - module and courses don't yet have Ids
		var courseModule = new CourseModule { CourseId = 1, ModuleId = 1 };
		context.CourseModules.Add(courseModule);
		courseModule = new CourseModule { CourseId = 1, ModuleId = 2};
		context.CourseModules.Add(courseModule);
		

		base.Seed(context)
	}
}

Open in new window

0
Comment
Question by:RBS
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 22

Expert Comment

by:ambience
ID: 39799525
Relying on Code first conventions, You could add virtual properties to the domain objects like

            public class Course
            {
                  public int Id { get; set; }
                  public string Name { get; set; }
                        public virtual ICollection<Module> Modules { get;set;}
            }

            public class Module
            {
                  public int Id { get; set; }
                  public string Name { get; set; }
                        public virtual ICollection<Course> Courses { get;set;}
            }

and then configure the model as

        protected override void OnModelCreating(DbModelBuilder b)
        {
            base.OnModelCreating(b);
            b.Entity<Course>().HasMany(p => p.Modules).WithMany(p => p.Courses);

This would allow you to seed like

var course = new Course(...)
var module = new Module(...)
course.Modules.Add(module);
module.Courses.Add(course);
0
 

Author Comment

by:RBS
ID: 39800138
Hi Ambience:

Thanks for the reply but it does not answer the question.  The problem is not with seeding the main tables but with seeding the join tables.  I have since found a good answer at http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

It looks something like this:

foreach (Enrollment e in enrollments)
            {
                var enrollmentInDataBase = context.Enrollments.Where(
                    s =>
                         s.Student.ID == e.StudentID &&
                         s.Course.CourseID == e.CourseID).SingleOrDefault();
                if (enrollmentInDataBase == null)
                {
                    context.Enrollments.Add(e);
                }
            }
            context.SaveChanges();

Open in new window


Regards,
RBS
0
 
LVL 22

Accepted Solution

by:
ambience earned 500 total points
ID: 39800673
Did you try it out?

It does seed the join table - automatically when you add module to course's collection of modules - and therefore it answers the question.

Querying the DB to re-read the entities and fill the jion table is an overkill. You should let EF manage that and the code I posted does that job.
0
 

Author Closing Comment

by:RBS
ID: 39801554
Thanks ambience!

RBS
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Change this SQL to get all nodes 3 38
VB.net/VSTO Excel Add-in 2 16
Need help with a query 14 37
What Is an Error? 2 24
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question