0

我正在用EF Code First開發ASP.NET MVC4應用程序。我在以下課程中擁有多對多的關係。我已經在我的上下文類中使用EF流利API定義了關係。但是我得到一個錯誤,因爲它試圖將值插入到我的主表中,涉及多對多關係。任何人都可以幫助我糾正我的問題。在此先感謝您寶貴的時間。我將庫模式和工作單元與Ninject一起用作依賴注入。 參與者類需要關於EF代碼的第一個流利的映射多對多

public class Participant 
    { 
     [Key] 
     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")] 
     [DisplayName("Birthday")] 
     [DataType(DataType.DateTime)] 
     public DateTime BirthDate { get; set; } 

     [DisplayName("Gender")] 
     [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; } 

    } 

興趣班

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

的DataContext

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) 
     { 
      modelBuilder.Entity<Participant>(). 
       HasMany(p => p.Interests). 
       WithMany(i => i.Participants). 
       Map(
        m => 
        { 
         m.ToTable("ParticipantInterests"); 
         m.MapLeftKey("ParticipantId"); 
         m.MapRightKey("InterestId"); 
        }); 
      modelBuilder.Entity<User>().HasRequired(u => u.Role); 
      modelBuilder.Entity<Participant>().HasRequired(p => p.Country); 
     } 


     public virtual void Commit() 
     { 
      base.SaveChanges(); 
     } 
    } 

控制器代碼

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>() }; 
         interest.Participants.Add(participant); 
         interests.Add(interest); 
        } 
        studentRegisterViewModel.Participant.Interests = interests; 
        _participantService.CreatParticipant(studentRegisterViewModel.Participant); 
        //_userService.CreatUser(studentRegisterViewModel.Participant.User); 
        //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 = 
       Enum.GetNames(typeof(Gender)).Select(
        x => new KeyValuePair<string, string>(x, x.ToString(CultureInfo.InvariantCulture))); 
      studentRegisterViewModel.Interests = _interestService.GetAllInterests(); 
      return View(studentRegisterViewModel); 
     } 

理想情況下,它應該在ParticipantInterests多對多表中插入參與者到參與者表和參與者興趣。但它給出了以下錯誤

{「無法將值NULL插入到'InterestName'列中,表'StudyTourNetworkDB.dbo.Interests';列不允許爲空,INSERT失敗。\ r \ n語句已終止。 「}

它試圖插入興趣表中,不應該發生。

參與者ParticipantInterests興趣 的ID編號 姓ParticipantId InterestName 名字InterestId

這是在數據庫中是如何的表。興趣表有一組固定的記錄(Study,Job,Other等),它們顯示在Interested In下拉列表中。註冊參與者可以選擇多個感興趣的選項,並且當他點擊註冊按鈕時,參與者記錄將被保存在參與者表中並且選擇參與者興趣表中的興趣。

謝謝

+0

對不起,錯誤到底是什麼? – ledgeJumper

回答

0

我在前幾天搞了一樣的東西。疼痛得到它想通了,但這裏是很多的一個非常基本的例子,很多我得到了工作:

namespace Project.Models 
{ 
    public class Affiliate 
    { 
     public Affiliate() 
     { 
      Merchants = new HashSet<Merchant>(); 
     } 
     public int Id { get; set; } 
     public ICollection<Merchant> Merchants { get; set; } 
    } 
} 


namespace Project.Models 
{ 
    public class Merchant 
    { 
     public Merchant() 
     { 
      Affiliates = new HashSet<Affiliate>(); 
     } 
     public int Id { get; set; } 
     public ICollection<Affiliate> Affiliates{ get; set; } 
    } 
} 

,並在的DbContext我這樣做:

  modelBuilder.Entity<Merchant>(). 
       HasMany(c => c.Affiliates). 
       WithMany(p => p.Merchants). 
       Map(
       m => 
       { 
        m.MapLeftKey("MerchantId"); 
        m.MapRightKey("AffiliateId"); 
        m.ToTable("MerchantAffiliates"); 
       }); 

更新

我想了解你在尋找什麼。看起來像這樣:

參與者可以對許多事情感興趣。多位參與者可能對同樣的事情感興趣。如果這是事實,我會考慮改變模型,讓參與者有興趣列表,但在我看來,興趣表不需要參與者名單。如果你想獲取說,在徒步旅行,你可能只是做這樣的事情感興趣所有參與者:

Context.Participants.ToList().Where(x => x.Interest.Name == "hiking"); 

有意義嗎?

+0

謝謝davidisawesome你的解決方案是絕對正確的,但我認爲我沒有精確地解釋這個問題。我已經更新了問題定義。非常感謝。 – pbhalchandra

+0

更新了答案。 – ledgeJumper

相關問題