我正在使用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; }
}
的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);
}
理想情况下,它应将参与者插入参与者表和参与者兴趣参与者感兴趣的多对多表。但它给出了以下错误
{&#34;无法将值NULL插入列&#39; InterestName&#39;,table&#39; StudyTourNetworkDB.dbo.Interests&#39;列不允许空值。 INSERT失败。\ r \ n语句已终止。&#34;}
它试图插入到Interests表中,这不应该发生。
参与者参与者利益 Id Id Id FirstName ParticipantId InterestName LastName InterestId
这是数据库中表的方式。兴趣表具有一组固定的记录(学习,工作,其他等),这些记录显示在“感兴趣的”下拉列表中。注册参与者可以选择多个感兴趣的选项,当他点击注册按钮时,参与者记录将保存在参与者表中,并选择参与者兴趣表中的兴趣。
由于
答案 0 :(得分: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");
有意义吗?