Reputation: 13
I get this error:
System.NullReferenceException: Object reference not set to an instance of an object
How can I resolve this exception?
Join query controller:
var Cs = new List<MyModel>();
using (Join3Entities1 db = new Join3Entities1())
{
DateTime start1 = DateTime.Now;
ViewBag.Start = "Start Time :" + start1;
Cs = (from e in db.Students
join p in db.Marks on e.S_ID equals p.S_ID
join t in db.Details on p.School_ID equals t.School_ID
where p.Score > 50
select new MyModel
{
S_Name = e.S_Name,
Score = (int)p.Score,
Status = p.Status,
Address_City = t.Address_City,
Email_ID = t.Email_ID,
Accomplishments = t.Accomplishments
}).ToList();
DateTime end1 = DateTime.Now;
ViewBag.end = "End Time:" + end1;
TimeSpan time1 = end1 - start1;
ViewBag.time = "TimeSpan:" + time1;
}
return View();
the above code is to join three table I wrote in controller section
model: public class MyModel { public string S_Name { get; set; } public int Score { get; set; } public string Status { get; set; } public string Address_City { get; set; } public string Email_ID { get; set; } public string Accomplishments { get; set; } }
view:
@model IEnumerable<Join3table.Models.MyModel>
@{
ViewBag.Title = "Home Page";
}
@foreach (var per in Model)
{
<tr>
<td>@per.S_Name</td>
<td>@per.Score</td>
<td>@per.Status</td>
<td>@per.Address_City</td>
<td>@per.Email_ID </td>
<td>@per.Accomplishments</td>
</tr>
}
</tbody>
</table>
I created three tables student,mark and details with primary and foreign key relation
Upvotes: 0
Views: 350
Reputation: 1707
instead of doing select new model
, try returning each table one by one to see where the nullref is specifically coming from, that way you might be able to narrow it down.
another option to be on the safe side is to make sure to nullrefcheck before calling each column S_Name = e != null && !string.isNullOrEmpty(e.S_Name) ? e.S_Name : string.Empty;
Upvotes: 0