在linq

时间:2017-01-22 23:02:10

标签: c# linq model-view-controller

我理解NullReferenceException是如何工作的。我不明白为什么它出现在我的代码中。

我有以下型号: 打字员:

public class Typer
{
    public string UserName { get; set; }
    public int Score { get; set; }

    public virtual ICollection<Typ> Typs { get; set; }
}

,典型值:

public class Typ
{
    public int TypId { get; set; }

    [Required]
    public string Wynik { get; set; }

    public int? TypGospodarze { get; set; }
    public int? TypGoscie { get; set; }

    public string UserName { get; set; }

    [ForeignKey("UserName")]
    public virtual Typer Typer { get; set; }

    public int MatchId { get; set; }
    public int? Points { get; set; }

    public virtual Match Match { get; set; }
}

和匹配:

public class Match
{
    public int MatchId { get; set; }

    public string HomeClubName { get; set; }
    public string AwayClubName { get; set; }

    public virtual Club HomeClub { get; set; }
    public virtual Club AwayClub { get; set; }

    public int? Club1Goals { get; set; }
    public int? Club2Goals { get; set; }

    public DateTime MatchDate { get; set; }

    public virtual ICollection<Typ> Typs { get; set; }
}

我现在不想改变它们。我尝试做的是使用ViewModel并能够在连接表中进行更改。首先,我要从TypId制作Typ的列表,然后在每个 List<int> idlist = db.Typ.Select(c => c.TypId).Distinct().ToList(); foreach (var item in idlist) { Points(item); } 上使用我的函数:

    public void Points(int idchecked)
    {
        var model = (from m in db.Match
                     join t in db.Typ on m.MatchId equals t.MatchId
                     join s in db.Typer on t.UserName equals s.UserName
                     select new TyperDataViewModel()
                     {
                         MatchId = m.MatchId,
                         Club1Goals = m.Club1Goals,
                         Club2Goals = m.Club2Goals,
                         Wynik = t.Wynik,
                         TypGospodarze = t.TypGospodarze,
                         TypGoscie = t.TypGoscie,
                         UserName = s.UserName,
                         Points = t.Points,
                         Score = s.Score
                     });

        var item = model.FirstOrDefault(i => i.MatchId == idchecked); //always null but why? Tables are not empty...
        if (item == null) { return; }
        else { item.Points = 2; }
 //...some code that uses rest of the fields will go here
    }

这是我职能的开始:

item

我添加了最后两行来检查Points是否始终为空,并且出于某种原因,它永远不会向Match添加2。从我理解我的代码

  

var item = model.FirstOrDefault(i =&gt; i.MatchId == idchecked);

应从MatchId中挑选一行idchecked等于First,但显然我一定是错的。当我使用FirstOrDefault代替NullReferenceException时,我不断获得if (model.Any()) {ViewBag.Check= "YES";} 。有什么帮助吗?表格不是空的。

编辑:我通过添加最简单的

来检查模型中是否存在任何内容
ScriptContext
它出现了,所以似乎linq中有记录。

0 个答案:

没有答案