【问题标题】:How to fetch all data using join three tables using Entity Framework如何使用实体框架连接三个表来获取所有数据
【发布时间】:2019-09-15 14:22:03
【问题描述】:

我收到此错误:

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 { 获取;放; } 公共 int 分数 { 获取;放; } 公共字符串状态{获取;放; } 公共字符串 Address_City { 获取;放; } 公共字符串 Email_ID { 获取;放; } 公共字符串成就{得到;放; } }

查看:

@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

【问题讨论】:

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


【解决方案1】:

不要执行select new model,而是尝试逐个返回每个表以查看 nullref 的具体来源,这样您可能可以缩小范围。

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

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 2017-10-06
    • 2018-06-30
    • 1970-01-01
    • 2011-06-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多