2015-09-05 95 views
1
public class kingdomAddModel 
{ 
    public string title { get; set; } 
    public string details { get; set; } 
    //public HttpPostedFileBase fileUpload { get; set; } 
    //public string retrieveFile { get; set; } 
    public FileAttr files { get; set; } 
} 

public class FileAttr 
{ 
    public HttpPostedFileBase fileUpload { get; set; } 
    public string retrieveFile { get; set; } 
} 

var getDailyDevotions = db.DailyDevotions.Select(d => new { title = d.DevotionsTitle, details = d.DevotionsDetails, retriveFileAudio = d.VoiceNotes }); 
List<kingdomAddModel> listdevotions = new List<kingdomAddModel>(); 
foreach (var getDevotions in getDailyDevotions) 
{ 
    kingdomlist = new kingdomAddModel(); 
    kingdomlist.title = getDevotions.title; 
    kingdomlist.details = getDevotions.details; 
    fileattr = new FileAttr(); 
    fileattr.retrieveFile = getDevotions.retriveFileAudio; 
    kingdomlist.files.retrieveFile = fileattr.retrieveFile; //erros appears here! 
} 

行線kingdomlist.files.retrieveFile的實例拋出異常,試着用搜索引擎但我不得到simular問題。我只是想分配價值,並會拉我的看法。分配值,以在控制器的複雜變量,我得到對象引用不設置爲一個對象

+0

你在哪裏初始化'kingdomlist.files'? –

+1

可能的重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – dotnetom

回答

1

請勿直接訪問FileAttr的屬性,只能使用fileskingdomAddModel的實例。不要的mixup他們

更換

foreach (var getDevotions in getDailyDevotions) 
{ 
    kingdomlist = new kingdomAddModel(); 
    kingdomlist.title = getDevotions.title; 
    kingdomlist.details = getDevotions.details; 
    fileattr = new FileAttr(); 
    fileattr.retrieveFile = getDevotions.retriveFileAudio; 
    kingdomlist.files.retrieveFile = fileattr.retrieveFile; //erros appears here! 
} 

foreach (var getDevotions in getDailyDevotions) 
{ 
    kingdomlist = new kingdomAddModel 
    { 
     title = getDevotions.title, 
     details = getDevotions.details, 
     files = new FileAttr 
     { 
      retrieveFile = getDevotions.retriveFileAudio, 
      //fileUpload = some value here 
     } 
    }; 
    listdevotions.Add(kingdomlist); 
} 

或使用Linq

listdevotions = (from getDevotions in getDailyDevotions 
       select new kingdomAddModel     
       { 
        title = getDevotions.title, 
        details = getDevotions.details, 
        files = new FileAttr 
        { 
         retrieveFile = getDevotions.retriveFileAudio, 
         //fileUpload = some value here 
        } 
       }).ToList(); 
相關問題