I wrote to following controller to assign one collection to another
public ActionResult Discussion_List() {
var discussions = (from D in db.AB_Discussion
select new
{
Discussion_ID = D.Discussion_ID,
Discussion_Name = D.Discussion_Name,
CreatedBy = D.CreatedBy,
CreatedDate = D.CreatedDate,
UpdatedBy = D.UpdatedBy,
UpdatedDate = D.UpdatedDate
}).ToList();
var models = discussions.Select(b => new Discussion_Dashboard()
{
Discussion_ID = b.Discussion_ID,
Discussion_Name = b.Discussion_Name,
CreatedBy = db.AspNetUsers.Find(b.CreatedBy).UserName,
CreatedDate = b.CreatedDate,
UpdatedBy = db.AspNetUsers.Find(b.UpdatedBy).UserName,
UpdatedDate = b.UpdatedDate
});
return View(models);
}
but when I have null values in any one of above field in database table AB_Discussion I'm getting following error
Object reference not set to an instance of an object.
How to avoid this error
this is my related model classes
public partial class Discussion_Dashboard
{
public int Discussion_ID { get; set; }
public string Discussion_Name { get; set; }
public string Discription { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public int Views { get; set; }
public int replys { get; set; }
}
public partial class AB_Discussion
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Discussion_ID { get; set; }
public string Discussion_Name { get; set; }
public string Discription { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public string UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
}
var discussions = (from D in db.AB_Discussion select D).ToList();UpdatedBy = b.UpdatedBy == null ? null : db.AspNetUsers.Find(b.UpdatedBy).UserName,