나는 EF Code First를 사용하여 ASP.NET MVC4 애플리케이션을 개발 중입니다. 나는 다음과 같은 수업들 사이에 다 대다 관계를 가지고있다. 컨텍스트 클래스에서 EF 유창 API를 사용하여 관계를 정의했습니다. 그러나 많은 - 투 - 많은 관계에 관련된 내 마스터 테이블 중 하나에 값을 삽입하려고 할 때 오류가 발생합니다. 아무도 내 문제를 해결할 수 있습니까? 미리 감사드립니다. 귀중한 시간을 위해. 의존성 주입으로 저장소 패턴과 작업 단위를 사용하고 있습니다. 참가자 클래스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);
}
이상적으로 Participant into Participant 테이블과 Participant Interests를 ParticipantInterests many-to-many 테이블에 삽입해야합니다. 그러나 다음과 같은 오류가 발생했습니다
{ " 'InterestName'열, 'StudyTourNetworkDB.dbo.Interests'테이블에 NULL 값을 삽입 할 수 없으며 열에는 null이 허용되지 않습니다. INSERT가 실패합니다. \ r \ n 문이 종료되었습니다. "}
관심을 가져야하는 테이블에 삽입하려고합니다.
참가자 ParticipantInterests는 이드 아이디 FIRSTNAME ParticipantId InterestName 성 InterestId
이 데이터베이스에서 어떻게 테이블입니다에게 관심사. 관심 분야 테이블에는 관심 분야 드롭 다운에 표시되는 고정 된 일련의 레코드 (학습, 직업, 기타 등)가 있습니다. 등록 참가자는 관심있는 옵션을 여러 개 선택할 수 있으며 가입 단추를 클릭하면 참가자 레코드가 참가자 테이블에 저장되고 선택한 관심 분야가 ParticipantInterests 테이블에 저장됩니다.
감사
죄송합니다. 정확히 무엇이 오류입니까? – ledgeJumper