Solved

Seeding a join table in MVC

Posted on 2014-01-21
4
285 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
  • 2
  • 2
4 Comments
 
LVL 22

Expert Comment

by:ambience
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks ambience!

RBS
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now