如何使用实体框架使用联接三个表获取所有数据

时间:2019-04-26 05:35:32

标签: c# asp.net-mvc razor entity-framework-6

我收到此错误:

  

System.NullReferenceException:对象引用未设置为对象的实例

如何解决此异常?

加入查询控制器:

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();

上面的代码是要连接我在控制器部分编写的三个表

型号:     公共类MyModel     {         公共字符串S_Name {get;组; }         public int得分{组; }         公共字符串状态{get;组; }         公共字符串Address_City {get;组; }         公用字符串Email_ID {get;组; }         公共字符串成就{组; }     }

视图:

@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>

我用主键和外键关系创建了三张表格student,mark和details

1 个答案:

答案 0 :(得分:0)

与其做select new model,而是尝试一张一张地返回每个表,以查看nullref的具体来源,这样您就可以缩小它的范围。

安全的另一种选择是确保在调用每一列S_Name = e != null && !string.isNullOrEmpty(e.S_Name) ? e.S_Name : string.Empty;之前确保nullrefcheck