Solved

Seeding a join table in MVC

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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Running total between 2 sql tables in Sql 6 50
CASE Statement using different fields 8 35
database audit for object access 6 42
sql server string_split 4 30
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

759 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