Click here to Skip to main content
13,051,404 members (47,612 online)
Rate this:
Please Sign up or sign in to vote.
I am developing an ASP.NET MVC4 application with EF Code First. I am having a many-to-many relationship among following classes. I have defined relationship using EF fluent api in my context class. But I am getting an error as it is trying to insert values into one of my master table involved in many-to-many relation. Can anyone help me correct my problem. Thanks in advance and for valuable time.I am using repository pattern and unit of work with Ninject as dependency injection. Participant Class

public class Participant
        public int Id { get; set; }
        [DisplayName("First Name")]
        [StringLength(50, ErrorMessage = "First name cannot be more than 50 characters")]
        [Required(ErrorMessage = "You must fill in first name")]
        public string FirstName { get; set; }
        [DisplayName("Last Name")]
        [StringLength(50, ErrorMessage = "Last name cannot be more than 50 characters")]
        [Required(ErrorMessage = "You must fill in last name")]
        public string LastName { get; set; }
        [Required(ErrorMessage = "You must indicate your full birthday")]
        public DateTime BirthDate { get; set; }
        [Required(ErrorMessage = "You must select gender")]
        public int Gender { get; set; }
        public string Address { get; set; }
        public int CountryId { get; set; }
        public Country Country { get; set; }
        [DisplayName("Zip code")]
        [StringLength(10, ErrorMessage = "Zip code cannot be more than 10 characters")]
        public string ZipCode { get; set; }
        public string Mobile { get; set; }
        public string PhotoUrl { get; set; }
        public int UserId { get; set; }
        public User User { get; set; }
        public virtual ICollection<Interest> Interests { get; set; }

Interest Class

public class Interest
        public int Id { get; set; }
        public string InterestName { get; set; }
        public virtual ICollection<Participant> Participants { get; set; }


public class STNDataContext : DbContext
        public DbSet<User> Users { get; set; }
        public DbSet<Participant> Participants { get; set; }
        public DbSet<Country> Countries { get; set; }
        public DbSet<Interest> Interests { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<SecurityQuestion> SecurityQuestions { get; set; }
        public DbSet<Tour> Tours { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
                HasMany(p => p.Interests).
                WithMany(i => i.Participants).
                    m =>
            modelBuilder.Entity<User>().HasRequired(u => u.Role);
            modelBuilder.Entity<Participant>().HasRequired(p => p.Country);

        public virtual void Commit()

Controller Code

public virtual ActionResult Register(StudentRegisterViewModel studentRegisterViewModel)
            if (ModelState.IsValid)
                if (_userService.IsUserExists(studentRegisterViewModel.Participant.User) == false)
                    // Attempt to register the user
                    //WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    //WebSecurity.Login(model.UserName, model.Password);
                    studentRegisterViewModel.Participant.User.Username = studentRegisterViewModel.Username;
                    studentRegisterViewModel.Participant.User.Email = studentRegisterViewModel.Email;
                    studentRegisterViewModel.Participant.User.DateCreated = DateTime.Now;
                    studentRegisterViewModel.Participant.User.Id = 3;
                    studentRegisterViewModel.Participant.User.IsApproved = false;
                    studentRegisterViewModel.Participant.User.RoleId = 2;
                    studentRegisterViewModel.Participant.CountryId = 1;
                    var participant = new Participant
                        Id = studentRegisterViewModel.Participant.Id,
                        FirstName = studentRegisterViewModel.Participant.FirstName,
                        LastName = studentRegisterViewModel.Participant.LastName,
                        Interests = new Collection<Interest>()
                    var interests = new List<Interest>();
                    foreach (var interestItem in studentRegisterViewModel.SelectedInterests)
                        var interest = new Interest { Id = interestItem, Participants = new Collection<Participant>() };
                    studentRegisterViewModel.Participant.Interests = interests;
                    //TODO: Need to check if do we need to register the user and get him signed-in. If yes signing in implementation goes here.
                    var user = _userService.GetUser(studentRegisterViewModel.Participant.User.Username);
                    //Session["User"] = user;
                    //FormsAuthentication.SetAuthCookie(user.Username, false);
                    //Growl("Welcome", "Thanks for registering and welcome to Truck Tracker.");
                    //return RedirectToAction("Index", "Home");
            //return RedirectToAction("Index", "Home");
            // If we got this far, something failed, redisplay form
            studentRegisterViewModel.Gender =
                    x => new KeyValuePair<string, string>(x, x.ToString(CultureInfo.InvariantCulture)));
            studentRegisterViewModel.Interests = _interestService.GetAllInterests();
            return View(studentRegisterViewModel);

Ideally it should insert Participant into Participants Table and Participant Interests in ParticipantInterests many-to-many table. But it is giving following error

{"Cannot insert the value NULL into column 'InterestName', table 'StudyTourNetworkDB.dbo.Interests'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

It is trying to insert into Interests table which should not happen.

Participant ParticipantInterests Interests
Id Id Id
FirstName ParticipantId InterestName
LastName InterestId

This is how the tables in the database. The Interest table has a fixed set of records(Study, Job, Other,etc) which get displayed in Interested In dropdown on sign-up form. The registering participant can select multiple interested in options while signing up and when he clicks Sign Up button the Participant record will get saved in Participant Table and selected Interests in ParticipantInterests table.

Posted 5-Dec-12 22:33pm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 6 Dec 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100