使用Entity Framework传递多个模型数据

时间:2017-08-22 09:16:13

标签: c# entity-framework

我有两张表格如下:

MatchDetails

MatchId MatchName TeamId1 TeamId2
1       Test      1       2

TeamDetails

TeamId TeamName
1      MyTeam  
2      YourTeam

现在我想要一份所有比赛的清单。

在我的MatchController我想要做的是:

CricketEntity db = new CricketEntity();

[HttpGet]
public ActionResult GetAllMatches()
{
     List<C_MatchDetails> listMatches = db.C_MatchDetails.ToList();

     return Json(new
     {
           success = "true",
           Message = "Data retrive successfully",
           ResposeData = listMatches
     },
     JsonRequestBehavior.AllowGet);
}

这只返回匹配详情。我希望将比赛详情填入其中的球队详细信息。

类似的东西:

MatchId MatchName TeamId1 TeamName1 TeamId2 TeamName2
1       Test      1       MyTeam    2       YourTeam 

提前致谢。

4 个答案:

答案 0 :(得分:1)

如果您将导航属性添加到MatchDetails课程,会让生活变得更轻松。

如果您设置了MatchDetails课程设置如下:

public class MatchDetails{
    public int MatchId { get; set; }
    public string MatchName { get; set; }
    public int TeamId1 { get; set; }
    public int TeamId2 { get; set; }
    public virtual TeamDetails Team1 { get; set; } // One new navigation property
    public virtual TeamDetails Team2 { get; set; } // Another new navigation property
}

使用Fluent API定义上下文类中的关系,如下所示:

modelBuilder.Entity<MatchDetails>()
    .HasRequired(m => m.Team1)
    .WithMany()
    .HasForeignKey(m => m.TeamId1);

modelBuilder.Entity<MatchDetails>()
    .HasRequired(m => m.Team2)
    .WithMany()
    .HasForeignKey(m => m.TeamId2);

然后你的LINQ变得更简单,不需要投射:

var listMatches = db.C_MatchDetails
  .Include(x => x.Team1)
  .Include(x => x.Team2)
  .ToList();

答案 1 :(得分:0)

您可以在返回连接表的db上创建存储过程。像这样 - &gt;&gt;

Select m.MatchId, m.MatchName, m.TeamId1, t.TeamName as TeamName1, m.TeamId2, t2.TeamName as TeamName2
from MatchDetails m inner join TeamDetails t on m.TeamId1=t.TeamId Inner join TeamDetails t2 on m.TeamId2=t2.TeamId

答案 2 :(得分:0)

使用Include以便EF在您获取数据时带回对团队的引用,例如:

... db.C_MatchDetails.Include(x =&gt; x.Team1).Include(x =&gt; x.Team2)。to list();

答案 3 :(得分:0)

你可以这样试试。

MatchDetails.Join(TeamDetails, x => new {x.TeamId , x.TeamId},
                     y => new {y.TeamId1 , y.TeamId2}, (x, y) => new 
{
x.name;
//////
////
});