0

我正在使用 EF Code First 开发 ASP.NET MVC4 应用程序。我在以下课程之间存在多对多关系。我在上下文类中使用 EF fluent api 定义了关系。但是我收到一个错误,因为它试图将值插入到我的一个涉及多对多关系的主表中。谁能帮我纠正我的问题。提前感谢您宝贵的时间。我正在使用存储库模式和 Ninject 的工作单元作为依赖注入。 参与者班级

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; }
    }

数据上下文

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);
        }

理想情况下,它应该将 Participant 插入 Participants 表和 ParticipantInterests 多对多表中的 Participant Interests。但它给出了以下错误

{"无法将值 NULL 插入到列 'InterestName'、表 'StudyTourNetworkDB.dbo.Interests';列不允许空值。INSERT 失败。\r\n语句已终止。"}

它试图插入不应该发生的兴趣表。

参与者 ParticipantInterests 兴趣 Id Id Id FirstName ParticipantId InterestName LastName InterestId

数据库中的表是这样的。兴趣表有一组固定的记录(学习、工作、其他等),这些记录显示在“感兴趣”下拉列表中。注册参与者可以选择多个感兴趣的选项,当他点击注册按钮时,参与者记录将保存在参与者表中,并在参与者兴趣表中选择兴趣。

谢谢

4

1 回答 1

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");

说得通?

于 2012-12-06T06:12:12.537 回答