2014-01-09 1 views
0

현재 Mvc 4 응용 프로그램에서 작업 중입니다. 내 컨트롤러 만들기는 다음과 같습니다. 각각개체 참조가 개체의 인스턴스로 설정되지 않았습니다.

public class OfficeCreateModel 
{ 
    public Guid Id { get; set; } 
    public string Name { get; set; } 
    public string Address1 { get; set; } 
    public string Address2 { get; set; } 
    public string Address3 { get; set; } 
    public string Telephone { get; set; } 
    public string Fax { get; set; } 
    public string Email { get; set; } 

    public Guid CompanyId { get; set; } 
    public bool IsDeleted { get; set; } 
} 


//DataModels 
public class Office 
{ 
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 
    [MaxLength(50)] 
    public string Name { get; set; } 
    [MaxLength(100)] 
    public string Address1 { get; set; } 
    [MaxLength(100)] 
    public string Address2 { get; set; } 
    [MaxLength(100)] 
    public string Address3 { get; set; } 
    [MaxLength(20)] 
    public string Telephone { get; set; } 
    [MaxLength(20)] 
    public string Fax { get; set; } 
    [MaxLength(255)] 
    public string Email { get; set; } 

    public Guid CompanyId { get; set; } 
    public virtual Company Company { get; set; } 
    public virtual List<Agent> Agents { get; set; }  
} 

는 개체의 나머지는 null를 돌려 ID와 이름 개체를 만드는 데 계속 코드를 실행 미터 돼 그래, 다음과 같이

[HttpPost] 
[ValidateAntiForgeryToken()] 
public ActionResult Create(OfficeCreateModels model) 
{ 
    bool success = false; 
    string message = ""; 

    try 
    { 
     if (model.Name.IsNullOrWhitespace()) throw new Exception("Unable to create this Office Name. The Type cannot be blank or spaces."); 

     var company = models.Companies.FirstOrDefault(x => x.Id == model.CompanyId); 

     var officeExist = models.Offices.Any(x => x.Name.ToLower() == model.Name.ToLower() && x.CompanyId == model.CompanyId); 

     if (officeExist) 
       throw new Exception(string.Format("Company '{0}' already has an Office this named '{1}'" .FormatWith(company.Name.ToUpperCase(), model.Name.ToUpperCase()))); 

     Office office = new Office 
     { 
      Name = model.Name.ToUpperCase(), 
      Address1 = model.Address1.ToUpperCase(), 
      Address2 = model.Address2.ToUpperCase(), 
      Address3 = model.Address3.ToUpperCase(), 
      Telephone = model.Telephone.ToUpperCase(), 
      Fax = model.Fax.ToUpperCase(), 
      Email = model.Email.ToUpperCase(), 
      AccountType = model.AccountType.ToUpperCase() 
     }; 

     models.Offices.Add(office); 
     models.SaveChanges(); 

     success = true; 
     return RedirectToAction("Index"); 
     } 
    catch (Exception ex) 
    { 
     message = ex.Message; 
    } 

    return View(model); 
} 

내 ViewModels 및 데이터 모델이다. l 단계 이상 진행되면 Name 만 값을 반환하고 나머지는 ViewModels에 null을 반환합니다. 누구든지 내 viewModels이 null 인 이유를 도울 수 있습니다. 미리 감사드립니다.

+2

작성보기의 모양은 무엇입니까? –

+0

모든 속성에 대해 ToUpperCase()를 호출하여 뷰 모델에 값이 있다고 가정합니다. 뷰 모델의 문자열이 'null'일 때 'NullReferenceException'이 발생합니다. –

답변

0
  1. Create의 서명에 OfficeCreateModels은 무엇입니까? OfficeCreateModel 클래스 만 게시했습니다.
  2. 메서드 본문의 변수 models은 무엇입니까? 메서드 본문에서는 변수 model 만 사용됩니다 (메서드의 서명에 선언되어 있음).

사용중인 변수를 살펴 보겠습니다. 이러한 변수가 초기화되지 않아 NullReference 예외가있는 것 같습니다.

+0

OfficeCreateModels은 ViewModels이고 변수 모델은 DBContext에 대한 참조입니다. – Muzingaye

+0

@Muzingaye 이제 나는 이해했다. 이 변수들이 초기화되었는지 확인 했습니까? –

+0

모든 변수가 private PMContext models = new PMContext()로 초기화되었습니다. 공용 클래스 PMContext 아래에 테이블과 같은 : DbContext { 공공 PMContext() : 기본 ("PMContext") { } 공공 DbSet 회사 {얻을; 세트; } public DbSet 사무실 {get; 세트; } public DbSet 요원 {get; 세트; } 정적 PMContext() { Database.SetInitializer (새 DropCreateDatabaseIfModelChanges ()); } } – Muzingaye

관련 문제