0

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

3
  • you should add your model and join query to question Commented Apr 26, 2019 at 6:17
  • 1
    Possible duplicate of What is a NullReferenceException, and how do I fix it? Commented Apr 26, 2019 at 6:34
  • i tried everthing but issue is not resolved Commented Apr 26, 2019 at 7:29

1 Answer 1

0

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;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.