Solved

Seeding a join table in MVC

Posted on 2014-01-21
4
291 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
I have a large data set and a SSIS package. How can I load this file in multi threading?
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

623 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