2014-09-15 2 views
0

메서드 GetContractor()를 호출하여 모든 속성을 반환하는 새 Contractor 개체 "gc"를 만듭니다. 반환하는 결과는 정확하지만 "gc"개체는 모두 "NULL"을 표시합니다. 내 aspx.cs 페이지에서 뭔가 잘못하고 있다고 가정합니까?클래스에서 반환 된 값이 null로 되돌아갑니다.

aspx.cs

protected void fvWasteCollected_ItemCommand(object sender, FormViewCommandEventArgs e) 
    { 
    if (e.CommandName.Equals("Insert")){ 
     ValidationSummaryWasteDetail.ValidationGroup = "WasteReceivedDetail"; 
     if (IsValid) { 
      odsMRWWasteCollectedDetail.InsertParameters["WasteTypeId"].DefaultValue = ddlWasteCollectedType.SelectedValue; 
      odsMRWWasteCollectedDetail.InsertParameters["DisposalMethodId"].DefaultValue = ddl_disposalMethod.SelectedValue;   
      Contractor gc = new Contractor(); 
      gc.GetContractor(2); 
      var contractorName = gc.MRWContractorName; 
     } 
    } 
} 

.cs

public class Contractor 
{ 
    public Contractor GetContractor(int MRWContractorId) 
    { 
     using (DataAccessLINQDataContext db = new DataAccessLINQDataContext()) 
     { 
      var result = db.MRWContractors.Where(c => c.MRWContractorId == MRWContractorId).Select(c => new Contractor 
       { 
        MRWContractorId = c.MRWContractorId, 
        MRWContractorName = c.MRWContractorName, 
        MRWContractorAddress = c.MRWContractorAddress, 
        MRWContractorCity = c.MRWContractorCity, 
        MRWContractorStateCode = c.MRWContractorStateCode, 
        MRWContractorZipCode = c.MRWContractorZipCode, 
        MRWContractorPhone = c.MRWContractorPhone, 
        MRWContractorFax = c.MRWContractorFax, 
        MRWContractorEmail = c.MRWContractorEmail 
       }).SingleOrDefault(); 

      return result; 
     } 
    } 

    public int MRWContractorId { get; set; } 
    public string MRWContractorName { get; set; } 
    public string MRWContractorAddress { get; set; } 
    public string MRWContractorCity { get; set; } 
    public string MRWContractorStateCode { get; set; } 
    public int? MRWContractorZipCode { get; set; } 
    public string MRWContractorPhone { get; set; } 
    public string MRWContractorFax { get; set; } 
    public string MRWContractorEmail { get; set; } 
} 

답변

3

당신이 뭔가에 할당 해달라고 할 때 gc의 가치를 잃어버린 있습니다.

대신을 시도해보십시오

var contractor = gc.GetContractor(2); 
var contractorName = contractor.MRWContractorName; 
1

를 당신 만 GetContractor 메소드를 호출하는 데 사용되는 객체의 하나 개의 빈 인스턴스를 만들 수 있습니다. GetContractor 메서드는 반환되는 데이터가 들어있는 다른 인스턴스를 만듭니다. 그러나 인스턴스를 버리고 데이터가 채워지지 않은 첫 번째 인스턴스에서 데이터를 사용할 수있을 것으로 기대합니다.

이제
public static Contractor GetContractor(int MRWContractorId) 

먼저 빈 인스턴스를 생성하지 않고, 데이터를 포함하는 인스턴스를 얻을 수있는 방법을 호출 할 수 있습니다 : 당신이 그것을 호출 인스턴스를 필요로하지 않도록

GetContractor 방법 정적 확인 :

Contractor gc = Contractor.GetContractor(2); 
string contractorName = gc.MRWContractorName; 
+0

여기에 나와있는 다른 방법이 마음에 들었습니다. 내 능력을 향상시키는 데 매우 도움이됩니다! 나는 가서 그것을 사용했다! – MSW

관련 문제